对比 Vue2 选项式 API 与 Vue3 setup 语法
对比 Vue2 选项式 API 与 Vue3 setup 语法
 
1. 代码组织方式
-  
Vue2 选项式 API
通过独立的选项(data,methods,computed,watch, 生命周期钩子等)组织代码。export default { data() { return { count: 0 }; }, methods: { increment() { this.count++; } }, mounted() { console.log('Component mounted'); } }问题:逻辑分散,一个功能的代码可能分布在多个选项中。
 -  
Vue3
setup语法
使用 Composition API 在setup函数内按逻辑组织代码,相关功能集中编写。import { ref, onMounted } from 'vue'; export default { setup() { const count = ref(0); const increment = () => { count.value++; }; onMounted(() => { console.log('Component mounted'); }); return { count, increment }; } }优势:逻辑内聚,便于复用(通过自定义 Hook)。
 
2. 响应式数据
-  
Vue2
使用data返回对象,Vue 自动递归处理为响应式。data() { return { user: { name: 'Alice' } }; } -  
Vue3
显式使用ref(基本类型)或reactive(对象)创建响应式数据。const count = ref(0); // 通过 .value 访问 const user = reactive({ name: 'Alice' }); // 直接访问属性 
3. 生命周期钩子
-  
Vue2
直接在选项中定义钩子(如mounted,created)。mounted() { console.log('Mounted'); } -  
Vue3
从vue导入钩子函数(如onMounted),在setup中使用。import { onMounted } from 'vue'; setup() { onMounted(() => { console.log('Mounted'); }); } 
4. 事件与 this
 
-  
Vue2
通过this访问数据/方法,使用this.$emit触发事件。methods: { handleClick() { this.$emit('click'); } } -  
Vue3
setup无this,通过context.emit触发事件。setup(props, { emit }) { const handleClick = () => { emit('click'); }; return { handleClick }; } 
5. 计算属性与侦听器
-  
Vue2
使用computed和watch选项。computed: { doubled() { return this.count * 2; } }, watch: { count(newVal) { console.log(newVal); } } -  
Vue3
使用computed和watch函数。import { computed, watch } from 'vue'; setup() { const doubled = computed(() => count.value * 2); watch(count, (newVal) => { console.log(newVal); }); return { doubled }; } 
setup 语法核心优势
 
- 逻辑复用
通过自定义 Hook(如useMouseTracker)封装逻辑,轻松跨组件复用。 - 更好的 TypeScript 支持
类型推断更友好,减少this的隐式类型问题。 - 更灵活的代码组织
相关逻辑集中管理,提升复杂组件的可维护性。 
常见问题与技巧
- 响应式丢失:解构 
reactive对象需用toRefs。const user = reactive({ name: 'Alice' }); const { name } = toRefs(user); // 保持响应式 - Ref vs Reactive: 
  
ref适用于基本类型,通过.value访问。reactive适用于对象,直接修改属性。
 
总结
- 选项式 API:适合简单场景,结构直观但逻辑分散。
 setup语法:适合复杂组件,逻辑集中且易于复用,需掌握响应式 API 的使用。
