Vue 3 Composition API 实战速记
定位
这篇笔记聚焦 setup 语法糖和组合式状态抽离
1. ref 和 reactive
1 | <script setup> |
要点:
- 基本类型用
ref - 对象结构用
reactive - 模板里会自动解包
ref
2. computed 和 watch
1 | <script setup> |
注意
computed 用于“派生值”,watch 用于“副作用”。
3. 组合式函数(composable)
1 | // composables/useCounter.ts |
1 | <script setup lang="ts"> |
4. 生命周期
1 | <script setup> |
5. 我的实践建议
团队规范建议
- 页面逻辑大于 80 行时,优先拆 composable。
- 组合函数命名统一为
useXxx。 - 副作用相关代码必须写清理逻辑。