vue如何实现计算
Vue 计算属性实现方法
计算属性(Computed Properties)是 Vue 中用于处理复杂逻辑的响应式属性,它会基于依赖的响应式数据自动缓存结果,只有当依赖发生变化时才重新计算。
基本语法
在 Vue 组件中定义计算属性:
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
}
}
计算属性缓存
计算属性会缓存结果,只有当依赖的响应式属性(如firstName或lastName)发生变化时才会重新计算。相比之下,方法调用会在每次渲染时都执行。
计算属性 vs 方法
使用方法实现相同功能:
methods: {
getFullName() {
return this.firstName + ' ' + this.lastName
}
}
区别在于计算属性有缓存,而方法每次都会执行。
计算属性的 setter
计算属性默认只有 getter,但也可以提供 setter:
computed: {
fullName: {
get() {
return this.firstName + ' ' + this.lastName
},
set(newValue) {
const names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
在模板中使用
计算属性可以像普通属性一样在模板中使用:
<p>{{ fullName }}</p>
计算属性依赖
计算属性可以依赖其他计算属性,形成依赖链:
computed: {
firstNameLength() {
return this.firstName.length
},
lastNameLength() {
return this.lastName.length
},
totalNameLength() {
return this.firstNameLength + this.lastNameLength
}
}
计算属性与侦听器
对于需要响应数据变化执行异步或开销较大的操作,使用侦听器(watch)可能更合适。计算属性更适合同步计算派生值。
在组合式 API 中使用
Vue 3 的组合式 API 中使用computed函数:

import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed(() => {
return firstName.value + ' ' + lastName.value
})






