vue实现computed
Vue 中实现 computed 计算属性
在 Vue 中,computed 是一种基于响应式依赖进行缓存的属性,适用于需要复杂逻辑计算的场景。computed 会根据依赖的数据自动更新,且只在相关依赖发生改变时才会重新计算。
基本用法
在 Vue 组件中,computed 可以以对象或函数的形式定义:

export default {
data() {
return {
firstName: '张',
lastName: '三'
}
},
computed: {
// 对象形式定义
fullName: {
get() {
return this.firstName + ' ' + this.lastName
},
set(newValue) {
const names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[1] || ''
}
},
// 函数形式定义(仅 getter)
reversedName() {
return this.fullName.split('').reverse().join('')
}
}
}
计算属性 vs 方法
计算属性是基于它们的响应式依赖进行缓存的,只有在相关依赖发生改变时才会重新求值。相比之下,方法调用总是会在重新渲染时再次执行函数。
// 方法调用会在每次渲染时执行
methods: {
getReversedName() {
return this.fullName.split('').reverse().join('')
}
}
// 计算属性会缓存结果,只有 fullName 变化时才重新计算
computed: {
reversedName() {
return this.fullName.split('').reverse().join('')
}
}
计算属性的 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] || ''
}
}
}
在组合式 API 中使用 computed
在 Vue 3 的组合式 API 中,使用 computed 函数:
import { ref, computed } from 'vue'
export default {
setup() {
const firstName = ref('张')
const lastName = ref('三')
// 只读计算属性
const fullName = computed(() => {
return firstName.value + ' ' + lastName.value
})
// 可写计算属性
const writableFullName = computed({
get() {
return firstName.value + ' ' + lastName.value
},
set(newValue) {
const names = newValue.split(' ')
firstName.value = names[0]
lastName.value = names[1] || ''
}
})
return {
firstName,
lastName,
fullName,
writableFullName
}
}
}
计算属性的最佳实践
计算属性适合用于需要复杂逻辑的数据转换,特别是当这个转换需要重复使用时。避免在计算属性中进行异步操作或副作用操作,这些场景更适合使用 watch 或方法。
对于大型项目,可以考虑将复杂的计算逻辑提取到单独的文件中,保持组件的简洁性。






