vue实现computed
Vue 中 computed 的实现原理
computed 属性是 Vue 的一个核心特性,它基于响应式依赖进行缓存,仅在依赖发生变化时重新计算。以下是 computed 的实现方式:
基本用法
在 Vue 组件中定义 computed 属性:
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
}
}
实现机制
computed 属性通过以下方式工作:
- 每个 computed 属性会被转换为一个 getter 函数
- Vue 会为 computed 属性创建一个 watcher 实例
- 当首次访问 computed 属性时,会执行计算并缓存结果
- 只有当依赖的响应式数据变化时,才会重新计算
与 methods 的区别
computed 属性与方法的主要区别在于缓存机制:
methods: {
getFullName() {
return this.firstName + ' ' + this.lastName
}
}
- computed 属性会缓存结果,只有依赖变化才重新计算
- 方法每次调用都会执行函数体
计算属性 setter
computed 属性也可以定义 setter:
computed: {
fullName: {
get() {
return this.firstName + ' ' + this.lastName
},
set(newValue) {
const names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[1] || ''
}
}
}
在 Composition API 中使用
Vue 3 的 Composition API 提供了 computed 函数:
import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed(() => {
return firstName.value + ' ' + lastName.value
})
// 可写计算属性
const writableFullName = computed({
get() {
return firstName.value + ' ' + lastName.value
},
set(newValue) {
[firstName.value, lastName.value] = newValue.split(' ')
}
})
性能优化建议
- 对于复杂计算,优先使用 computed 而非 methods
- 避免在 computed 中执行副作用操作
- 对于不依赖响应式数据的计算,使用普通函数更高效
- 大型项目可考虑使用 memoization 技术进一步优化







