computed vue 实现
computed 的基本用法
在 Vue 中,computed 用于声明计算属性,基于响应式依赖进行缓存计算。当依赖的响应式数据变化时,计算属性会自动重新计算。
const app = Vue.createApp({
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
}
})
computed 的 setter 和 getter
计算属性默认只有 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 在 Composition API 中的使用
在 Vue 3 的 Composition API 中,使用 computed 函数创建计算属性。
import { ref, computed } from 'vue'
setup() {
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed(() => {
return firstName.value + ' ' + lastName.value
})
return {
fullName
}
}
computed 的响应式依赖
计算属性会自动追踪响应式依赖,当这些依赖发生变化时,计算属性会重新计算。
computed: {
reversedMessage() {
return this.message.split('').reverse().join('')
}
}
computed 的性能优化
由于计算属性会缓存结果,只有当依赖变化时才重新计算,因此比在模板中使用复杂表达式或频繁调用 methods 更高效。
computed: {
filteredItems() {
return this.items.filter(item => item.isActive)
}
}
computed 的异步操作
计算属性默认不支持异步操作,需要结合其他 API 如 async/await 或使用 watch 来实现。

computed: {
asyncComputed: {
get() {
return Promise.resolve('Async Value')
},
set() {}
}
}






