vue computed 实现
computed 的基本用法
在 Vue 中,computed 用于声明计算属性,这些属性基于响应式依赖进行缓存。只有当依赖发生变化时,计算属性才会重新计算。
new Vue({
data: {
firstName: '张',
lastName: '三'
},
computed: {
fullName: function() {
return this.firstName + ' ' + this.lastName
}
}
})
computed 的 getter 和 setter
计算属性默认只有 getter,但也可以提供 setter 方法。
computed: {
fullName: {
get: function() {
return this.firstName + ' ' + this.lastName
},
set: function(newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
computed 与 methods 的区别
计算属性是基于它们的响应式依赖进行缓存的,只有在相关依赖发生改变时才会重新求值。相比之下,每当触发重新渲染时,methods 调用总会执行函数。
methods: {
getFullName: function() {
return this.firstName + ' ' + this.lastName
}
}
computed 与 watch 的区别
watch 更适用于数据变化时执行异步或开销较大的操作。computed 更适合同步计算派生值。
watch: {
firstName: function(val) {
this.fullName = val + ' ' + this.lastName
},
lastName: function(val) {
this.fullName = this.firstName + ' ' + val
}
}
Vue 3 中的 computed
在 Vue 3 中,可以使用 computed 函数来创建计算属性。
import { ref, computed } from 'vue'
setup() {
const firstName = ref('张')
const lastName = ref('三')
const fullName = computed(() => {
return firstName.value + ' ' + lastName.value
})
return {
fullName
}
}
computed 的依赖追踪
计算属性会自动追踪其依赖关系,当依赖的响应式属性变化时,计算属性会自动更新。这使得计算属性非常高效,避免了不必要的重复计算。
computed 的缓存机制
计算属性的结果会被缓存,除非依赖的响应式属性发生变化,否则多次访问计算属性会立即返回缓存结果,而不会重新执行计算函数。







