组合式 API 和选项式 API 是?Vue.js?提供的两种不同的 API。组合式 API 更加灵活,在处理复杂场景时更有效,而选项式 API 则更易于入门和使用,适合处理简单的场景。下面是组合式 API 和选项式 API 的一个比较:
<template>
<div>
<p>{{ title }}</p>
<button @click="increaseCount">点击按钮 +1</button>
<p>当前计数: {{ count }}</p>
</div>
</template>
<script>
import { reactive, computed, watch } from 'vue';
export default {
setup() {
const data = reactive({
title: '使用组合式 API',
count: 0,
});
const increaseCount = () => {
data.count++;
};
const doubleCount = computed(() => {
return data.count * 2;
});
watch(
() => data.count,
(newCount, oldCount) => {
console.log(`计数从 ${oldCount} 变为 ${newCount}`);
}
);
return {
title: data.title,
count: data.count,
increaseCount,
doubleCount,
};
},
};
</script>
<template>
<div>
<p>{{ title }}</p>
<button @click="increaseCount">点击按钮 +1</button>
<p>当前计数: {{ count }}</p>
</div>
</template>
<script>
export default {
data() {
return {
title: '使用选项式 API',
count: 0,
};
},
methods: {
increaseCount() {
this.count++;
},
},
computed: {
doubleCount() {
return this.count * 2;
},
},
watch: {
count(newCount, oldCount) {
console.log(`计数从 ${oldCount} 变为 ${newCount}`);
},
},
};
</script>