Vue3 setup代替了vue2的哪些功能
文章目录
- 1. 替代 data():定义响应式数据
- 2. 替代 methods:定义方法
- 3. 替代 computed:计算属性
- 4. 替代生命周期钩子(如 created、mounted 等)
- 5. 替代 props 和 $emit:父子组件通信
- 6. 替代 watch:数据监听
- 核心差异总结
Vue3 的 setup 函数(或 <script setup>
语法糖)是 Composition API
的核心入口,它替代了 Vue2 中 Options API
的多个核心功能,实现了更灵活的代码组织方式。具体替代关系如下:
1. 替代 data():定义响应式数据
Vue2:通过 data() 函数返回响应式数据对象。
export default {data() {return {count: 0,user: { name: 'Alice' }};}
};
Vue3 setup:通过 ref/reactive 直接定义响应式数据,无需包裹在 data() 中。
import { ref, reactive } from 'vue';export default {setup() {const count = ref(0); // 基本类型响应式const user = reactive({ name: 'Alice' }); // 对象类型响应式return { count, user }; // 暴露给模板}
};
2. 替代 methods:定义方法
Vue2:在 methods 对象中定义方法,通过 this 访问数据。
export default {data() { return { count: 0 }; },methods: {increment() {this.count++; // 依赖 this 上下文}}
};
Vue3 setup:直接在 setup 中定义函数,通过闭包访问响应式数据(无需 this)。
import { ref } from 'vue';export default {setup() {const count = ref(0);const increment = () => {count.value++; // 直接访问变量,无需 this};return { count, increment };}
};
3. 替代 computed:计算属性
Vue2:在 computed 对象中定义计算属性。
export default {data() { return { count: 0 }; },computed: {doubleCount() {return this.count * 2;}}
};
Vue3 setup:通过 computed 函数创建计算属性。
import { ref, computed } from 'vue';export default {setup() {const count = ref(0);const doubleCount = computed(() => count.value * 2); // 函数式定义return { count, doubleCount };}
};
4. 替代生命周期钩子(如 created、mounted 等)
Vue2:通过选项定义生命周期钩子。
export default {created() {console.log('组件创建完成');},mounted() {console.log('组件挂载完成');}
};
Vue3 setup:通过 onXxx 系列函数(如 onMounted)注册生命周期,需手动导入。
import { onCreated, onMounted } from 'vue';export default {setup() {onCreated(() => {console.log('组件创建完成');});onMounted(() => {console.log('组件挂载完成');});}
};
注:setup 本身在 beforeCreate 和 created 之间执行,因此 onCreated 可直接在 setup 中写逻辑替代。
5. 替代 props 和 $emit:父子组件通信
Vue2:通过 props 选项接收父组件数据,通过 this.$emit 触发事件。
export default {props: {title: { type: String, required: true }},methods: {handleClick() {this.$emit('change', 'new value'); // 触发事件}}
};
Vue3 setup:通过 setup 的参数接收 props 和 emit。
export default {props: {title: { type: String, required: true }},setup(props, { emit }) { // 第一个参数是 props,第二个参数含 emitconst handleClick = () => {emit('change', 'new value'); // 直接调用 emit,无需 this};return { handleClick };}
};
6. 替代 watch:数据监听
Vue2:通过 watch 选项监听数据变化。
export default {data() { return { count: 0 }; },watch: {count(newVal, oldVal) {console.log(`count 从 ${oldVal} 变为 ${newVal}`);}}
};
Vue3 setup:通过 watch 或 watchEffect 函数监听。
import { ref, watch } from 'vue';export default {setup() {const count = ref(0);watch(count, (newVal, oldVal) => { // 显式指定监听对象console.log(`count 从 ${oldVal} 变为 ${newVal}`);});return { count };}
};
核心差异总结
Vue2 的 Options API 强制将代码按 “数据(data)、方法(methods)、生命周期(hooks)” 等分类,而 setup 允许按 “业务逻辑” 组织代码(如将相关的数据、方法、监听逻辑放在一起),更适合复杂组件。
简单说:setup 以函数式编程的方式,统一替代了 Vue2 中 data、methods、computed、watch、生命周期钩子等核心功能,同时提供了更灵活的代码组织能力。