Vue3$Data-Computed
0. computed in Big Picture
数据可以分为基础数据和衍生数据。比如姓名“张三”的姓和名(“张”和“三”)为基础数据,姓名(“张三”)为衍生数据。
基础数据中的响应数据,Vue 中可以通过ref和reactive来表示。(非响应数据通过普通js对象来表示)
对于衍生数据,如果希望其也具有响应式,则需要通过computed来表示。(computed中使用的数据也可以都是非响应式数据,但是如此一来,computed返回的值就固定了。)
computed 的值是缓存的,只要依赖不变就不会重新计算。
1. Function 形式的 computed
computed可以接受一个函数,这个函数的返回值就是一个具有响应式的衍生数据 computed ref。
// a computed ref
// 1. function. Argument: oldValue: T | undefined
const fullNameGetter = computed(() => {
return firstName.value + ' ' + lastName.value
})
2. Object 形式的 computed
Function 形式的 computed 只能进行读取。如果想要设置,则需要传入一个包含get和set的对象。但是从“衍生数据”这个用途来说,不应该对 computed 的值进行修改。
// 2. object
const fullName = computed({
// getter
get() {
return firstName.value + ' ' + lastName.value
},
// setter
set(newValue) {
[firstName.value, lastName.value] = newValue.split(' ')
}
})
3. 非响应式的 computed
// never update
const now = computed(() => Date.now())