背景 Vue3 发布两年多了,从 Options API 迁移到 Composition API 的项目也有了不少。这里总结一些实战经验。
为什么需要 Composition API Options API 的问题:逻辑关注点分散在一个组件的各个选项里(data、methods、computed、watch…)。
// Options API - 逻辑分散 export default { data() { return { count: 0 } }, methods: { increment() { this.count++ } }, computed: { doubled() { return this.count * 2 } }, watch: { count(newVal) { console.log('count changed:', newVal) } } } <!-- Composition API - 逻辑内聚 --> <script setup> import { ref, computed, watch } from 'vue' const count = ref(0) const doubled = computed(() => count.value * 2) const increment = () => count.value++ watch(count, (newVal) => { console.log('count changed:', newVal) }) </script> 实用技巧 1. ref vs reactive 该用哪个? // primitive types (String, Number, Boolean) -> ref const name = ref('BvBeJ') const age = ref(18) // objects/arrays -> reactive const user = reactive({ name: 'BvBeJ', skills: ['Go', 'Rust', 'C++'] }) // 或者对象也用 ref,通过 .value 访问 const user = ref({ name: 'BvBeJ' }) user.value.name = 'New Name' // 需要 .value 我的习惯: 简单类型用 ref,复杂对象用 reactive。TypeScript 类型推导更清晰。
...