computed vue 实现
computed 在 Vue 中的基本用法
Vue 的 computed 属性用于声明依赖于其他数据的计算属性。当依赖的数据变化时,计算属性会自动重新计算并缓存结果。
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`
}
}
}
fullName 会根据 firstName 和 lastName 的变化自动更新,且仅在依赖变化时重新计算。
computed 的缓存特性
计算属性会基于依赖的响应式数据缓存结果。只有当依赖的数据(如 firstName 或 lastName)变化时,computed 才会重新计算。多次访问 fullName 只会触发一次计算。
console.log(this.fullName) // 计算一次
console.log(this.fullName) // 直接返回缓存
computed 的 setter 方法
默认情况下,computed 是只读的,但可以通过定义 set 方法实现可写性。
computed: {
fullName: {
get() {
return `${this.firstName} ${this.lastName}`
},
set(newValue) {
const [first, last] = newValue.split(' ')
this.firstName = first
this.lastName = last
}
}
}
调用 this.fullName = 'Jane Smith' 会触发 set 方法,更新 firstName 和 lastName。
computed 与 methods 的区别
- 计算属性 (
computed):基于依赖缓存,适合复杂计算或频繁访问的数据。 - 方法 (
methods):每次调用都会重新执行,适合需要实时计算的场景。
methods: {
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
getFullName() 每次调用都会执行,而 computed 的 fullName 会缓存结果。
在 Vue 3 中使用 computed
Vue 3 的 Composition API 通过 computed 函数实现计算属性。
import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed(() => `${firstName.value} ${lastName.value}`)
fullName 会响应 firstName 或 lastName 的变化。
computed 的依赖追踪
计算属性会自动追踪所有在计算过程中使用的响应式数据。如果依赖的数据未被使用(如条件分支中未执行的代码),则不会触发更新。
computed: {
example() {
if (this.flag) {
return this.dataA // 仅当 flag 为 true 时依赖 dataA
}
return this.dataB
}
}
性能优化建议
- 避免在
computed中执行高开销操作(如循环或异步请求)。 - 拆分复杂计算为多个
computed属性,提高可读性和维护性。 - 在 Vue 3 中,使用
computed的缓存特性减少不必要的渲染。







