在计算属性内,get/set字面意思是获取和设置操作,计算属性值根据依赖变量的值在get内return,set则是值改变时需要执行的区域。
<template>
<div class="hello">
<div class="t1">{{ a }}</div>
<div class="t2">{{ b }}</div>
<button @click="change1">btn-1</button>
<button @click="change2">btn-2</button>
</div>
</template>
export default {
data() {
return {
a: 1,
};
},
mounted() {},
computed: {
b: {
set: function (newValue) {
console.log("--computed--set--", newValue);
},
get: function () {
console.log("--computed--get--", this.a);
return `${this.a}-2143`;
},
},
},
methods: {
change1() {
this.a++;
},
change2() {
this.b = this.b.substring(1);
},
},
};
常规的computed写法,如果b变量在某个地方被更改的话,会报错。
computed: {
b (){
return `${this.a}-211243`;
}
},