computed vue 实现
computed 的基本用法
在 Vue 中,computed 用于声明计算属性,基于响应式依赖进行缓存。只有当依赖发生变化时才会重新计算。
export default {
data() {
return {
firstName: '张',
lastName: '三'
}
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
}
}
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: {
now() {
return Date.now() // 不会更新,因为不是响应式依赖
}
}
与方法的区别
方法每次调用都会执行函数,而计算属性会缓存结果。
methods: {
getFullName() {
return this.firstName + ' ' + this.lastName // 每次调用都会执行
}
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName // 依赖不变时返回缓存
}
}
在组合式 API 中使用
Vue 3 的组合式 API 中使用 computed 需要从 vue 导入。
import { ref, computed } from 'vue'
const firstName = ref('张')
const lastName = ref('三')
const fullName = computed(() => {
return firstName.value + ' ' + lastName.value
})
计算属性调试
可以给计算属性添加 onTrack 和 onTrigger 选项来调试。
const fullName = computed({
get() {
return firstName.value + ' ' + lastName.value
},
set(newValue) {
[firstName.value, lastName.value] = newValue.split(' ')
},
onTrack() {
console.log('fullName 被追踪')
},
onTrigger() {
console.log('fullName 被触发')
}
})
计算属性与侦听器
计算属性适合用于派生状态,而侦听器适合在状态变化时执行异步或开销较大的操作。

watch(fullName, (newVal, oldVal) => {
console.log(`全名从 ${oldVal} 变为 ${newVal}`)
})
计算属性的性能优化
避免在计算属性中进行复杂的计算或循环操作。对于大型列表,考虑使用分页或虚拟滚动。






