vue computed 实现
computed 的基本用法
在 Vue 中,computed 用于声明计算属性,它会根据依赖的响应式数据自动计算并缓存结果。当依赖的数据变化时,计算属性会重新计算。
export default {
data() {
return {
firstName: '张',
lastName: '三'
}
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
}
}
computed 的 getter 和 setter
计算属性默认只有 getter,但也可以提供 setter 方法。

computed: {
fullName: {
get() {
return this.firstName + ' ' + this.lastName
},
set(newValue) {
const names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[1] || ''
}
}
}
computed 与 methods 的区别
计算属性是基于它们的响应式依赖进行缓存的,只有在相关依赖发生改变时才会重新计算。而 methods 每次调用都会执行函数。

methods: {
getFullName() {
return this.firstName + ' ' + this.lastName
}
}
computed 与 watch 的区别
watch 用于观察和响应数据的变化,适用于需要在数据变化时执行异步或开销较大的操作。computed 适用于基于现有数据计算新值的场景。
watch: {
firstName(newVal) {
this.fullName = newVal + ' ' + this.lastName
},
lastName(newVal) {
this.fullName = this.firstName + ' ' + newVal
}
}
computed 在 Vue 3 中的变化
在 Vue 3 中,computed 可以通过组合式 API 使用,返回一个 ref 对象。
import { ref, computed } from 'vue'
export default {
setup() {
const firstName = ref('张')
const lastName = ref('三')
const fullName = computed(() => {
return firstName.value + ' ' + lastName.value
})
return {
fullName
}
}
}
computed 的最佳实践
计算属性应保持纯粹,避免在其中执行副作用操作。复杂的计算逻辑可以拆分为多个计算属性,提高代码可读性和维护性。






