Vue3 选项式 API
选项式 API(Options API)是 Vue 最经典的组件写法:状态放进 data、方法放进 methods、派生值放进 computed、响应变化交给 watch,每个「选项」各司其职。Vue3 完全兼容这套写法,对结构简单、逻辑不复杂的组件而言依然直观好维护。
最小组件:data 与 methods
<script>
export default {
data() {
return { count: 0 } // 状态
},
methods: {
add() {
this.count++ // 方法里通过 this 读写 data
},
},
}
</script>
<template>
<p>{{ count }}</p>
<button @click="add">加一</button>
</template>
data 必须写成函数并返回对象,这样每个组件实例才有独立状态;模板可直接访问 data 与 methods。
computed 与 watch
computed 缓存派生结果,watch 侦听数据变化并执行副作用:
export default {
data() {
return { price: 100, quantity: 2 }
},
computed: {
total() {
return this.price * this.quantity // 依赖变化时自动重算
},
},
watch: {
price(newVal, oldVal) {
console.log(`价格 ${oldVal} → ${newVal}`) // 输出:价格 100 → 120
},
},
}
模板中直接写 {{ total }} 即可显示计算结果。
组件通信:props 与 emits
父传子用 props,子传父用 emits 声明事件后再触发:
export default {
name: 'ProductCard',
props: {
title: { type: String, required: true }, // 父组件传入
price: Number,
},
emits: ['add-to-cart'], // 声明自定义事件
methods: {
handleAdd() {
this.$emit('add-to-cart', this.title) // 通知父组件
},
},
}
模板中用 {{ title }}、{{ price }} 展示数据,点击按钮触发事件;父组件以 <product-card :title="商品名" @add-to-cart="加入购物车" /> 对接即可。
生命周期选项
同名选项函数会在对应阶段被自动调用:
export default {
created() {
console.log('实例已创建') // 输出:实例已创建
},
mounted() {
console.log('已挂载,可操作 DOM') // 输出:已挂载,可操作 DOM
},
beforeUnmount() {
console.log('即将卸载,做清理') // 输出:即将卸载,做清理
},
}
用法与 Vue2 几乎一致,老项目迁移成本很低。
如何选择
- 组件简单、状态不多,或团队习惯 Vue2 写法 → 选选项式 API。
- 逻辑复杂、需要抽取复用、重度使用 TypeScript → 选组合式 API。
- 两者也可在同一组件并存:选项式外壳里套一个 setup 函数。
小结
选项式 API 把组件拆成 data、methods、computed、watch 等固定选项,规则清晰、上手快。Vue3 保留它的同时新增组合式 API,两种风格相辅相成,按项目场景选择即可。