计算属性的结果会被缓存,除非依赖的响应式 property 变化才会重新计算。注意,如果某个依赖 (比如非响应式 property) 在该实例范畴之外,则计算属性是不会被更新的。
data() {
return {
num: 10
}
},
computed:{
numDouble(){
return this.num * 2
},
numPlus: {
get() {
console.log("调用了一次numPlus")
return this.num + 1
},
set(val) {
this.num = val -1
}
}
},
init(){
console.log("this.numDouble", this.numDouble) // this.numDouble 20
console.log("this.num", this.num) // this.num 10
console.log("this.numPlus", this.numPlus) // this.numPlus 11; 在计算方法中输出: 调用了一次numPlus;
console.log("this.num", this.num) // this.num 10
this.numPlus = 15
console.log("this.num", this.num) // this.num 14
console.log("this.numDouble", this.numDouble) // this.numDouble 28
console.log("this.numPlus", this.numPlus) // this.numPlus 15; 在计算方法中输出: 调用了一次numPlus;
console.log("this.numPlus", this.numPlus) // this.numPlus 15
console.log("this.numPlus", this.numPlus) // this.numPlus 15
}
下面是输出结果:
myComputed.vue?134f:42 this.numDouble 20
myComputed.vue?134f:43 this.num 10
myComputed.vue?134f:23 调用了一次numPlus
myComputed.vue?134f:44 this.numPlus 11
myComputed.vue?134f:45 this.num 10
myComputed.vue?134f:47 this.num 14
myComputed.vue?134f:48 this.numDouble 28
myComputed.vue?134f:23 调用了一次numPlus
myComputed.vue?134f:49 this.numPlus 15
myComputed.vue?134f:50 this.numPlus 15
myComputed.vue?134f:51 this.numPlus 15
网友评论