选项式 API(Options API) 和 组合式 API(Composition API) 是 Vue.js 中两种不同的组件代码组织方式。Vue2 主要使用选项式 API,而 Vue3 引入了组合式 API,提供了更灵活的逻辑组织和复用方式。以下是它们的详细对比:
1. 选项式 API(Options API)
选项式 API 是 Vue2 的主要编程方式,通过定义不同的选项(如 data
、methods
、computed
等)来组织代码。
代码结构
export default {
data() {
return {
count: 0,
};
},
methods: {
increment() {
this.count++;
},
},
computed: {
doubleCount() {
return this.count * 2;
},
},
mounted() {
console.log('Component mounted');
},
};
特点
-
代码分块:逻辑分散在
data
、methods
、computed
等选项中。 -
易于上手:适合初学者,结构清晰。
-
逻辑复用:通过 Mixins 实现,但可能导致命名冲突和来源不清晰。