vue中怎么实现计算
计算属性(Computed Properties)的基本用法
在 Vue 中,计算属性通过 computed 选项定义。计算属性是基于它们的依赖进行缓存的,只有依赖发生变化时才会重新计算。
new Vue({
data: {
firstName: 'John',
lastName: 'Doe'
},
computed: {
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
}
})
计算属性的缓存特性
计算属性会缓存计算结果,只有当依赖的响应式属性变化时才会重新计算。相比之下,方法调用会在每次渲染时都执行。

computed: {
now: function() {
return Date.now() // 不会更新,因为不是响应式依赖
}
}
计算属性的 Setter
计算属性默认只有 getter,但也可以提供 setter。
computed: {
fullName: {
get: function() {
return this.firstName + ' ' + this.lastName;
},
set: function(newValue) {
var names = newValue.split(' ');
this.firstName = names[0];
this.lastName = names[names.length - 1];
}
}
}
计算属性 vs 方法
方法会在每次调用时执行,而计算属性会缓存结果。对于开销大的计算,使用计算属性更高效。

methods: {
reversedMessage: function() {
return this.message.split('').reverse().join('');
}
}
计算属性 vs 侦听属性
侦听属性(watch)适合在数据变化时执行异步或开销较大的操作,而计算属性适合同步计算派生值。
watch: {
firstName: function(val) {
this.fullName = val + ' ' + this.lastName;
},
lastName: function(val) {
this.fullName = this.firstName + ' ' + val;
}
}
计算属性的依赖追踪
计算属性会自动追踪响应式依赖。如果依赖是非响应式的(如不在 data 中定义),计算属性不会更新。
data: {
object: {
nonReactiveProp: 'value'
}
},
computed: {
value: function() {
return this.object.nonReactiveProp // 不会更新
}
}






