首先:什么时候使用computed?

(1)当computed属性依赖于其他一个或者多个“被依赖值“的时候就使用computed,

(2)其中computed属性不需要定义,被依赖值需要定义

(3)当被依赖值发生变化时,computed属性随时更新。

ue 2 和 Vue 3 中 computed 的使用有一些区别,但核心功能相同。在 Vue 2 中,computed 属性可以定义为一个函数或一个对象,而在 Vue 3 中,它们被重写为仅使用函数。

Vue 2 中的 computed 属性可以是一个对象,其中包括 get 和 set 函数,或者是一个简单的函数,用于返回一个依赖于其他响应式属性的值。

// Vue 2 使用对象形式的 computed 属性
computed: {
fullName: {
get() {
return this.firstName + ' ' + this.lastName;
},
set(value) {
[this.firstName, this.lastName] = value.split(' ');
}
}
}
 
// Vue 2 使用函数形式的 computed 属性
computed: {
fullName() {
return this.firstName + ' ' + this.lastName;
}
}

// Vue 3 中的 computed 属性
import { computed } from 'vue';

export default {
setup() {
const firstName = ref('John');
const lastName = ref('Doe');

// 使用 computed 函数创建一个计算属性
const fullName = computed({
get: () => firstName.value + ' ' + lastName.value,
set: (value) => {
[firstName.value, lastName.value] = value.split(' ');
}
});

// 如果不需要 setter,可以简化为只读的 computed property
const fullNameReadOnly = computed(() => firstName.value + ' ' + lastName.value);

return {
firstName,
lastName,
fullName,
fullNameReadOnly
};
}
}