Vue2中的computed
在 Vue 2 中,computed 是通过选项式 API 实现的,通常在组件的 computed 选项中定义。
【基本用法】
export default {
data() {
return {
firstName: 'Alice',
lastName: 'Smith',
};
},
computed: {
// 计算属性:全名
fullName() {
return this.firstName + ' ' + this.lastName;
},
},
};
Vue3中的computed
在 Vue 3 中,computed 是通过 Composition API 实现的,使用 computed 函数来定义计算属性。
import { ref, computed } from 'vue';
export default {
setup() {
const firstName = ref('Alice');
const lastName = ref('Smith');
// 计算属性:全名
const fullName = computed(() => {
return firstName.value + ' ' + lastName.value;
});
return {
firstName,
lastName,
fullName,
};
},
};