computed计算属性和watch侦听器例子
<h2>计算属性和侦听器</h2>
<input type="text" class="flex_l mt-20" v-model="name1" />
<input type="text" class="flex_l mt-20" v-model="name2" />
<input type="text" class="flex_l mt-20" v-model="name" />
data() {
return {
name1: "",
name2: "",
// name: "" //computed的变量不能再data中定义,但watch需要定义
};
},
computed: {
name: {
get() { //name1和name2变化引起name变化
return this.name1 + "--" + this.name2; //或者可以只有get
},
set(newV) { //name变化,设置name1和name2的值
this.name1 = newV.split("--")[0];
this.name2 = newV.split("--")[1];
this.tip();
}
}
},
watch: {
name1(newV) {
if (!newV || !this.name2) {
this.tip();
} else {
this.name = this.name1 + this.name2;
}
}
},
tip() {
this.$toast("还有一个没填哦");
},
比较
1、watch 选项允许我们执行异步操作 (访问一个 API),限制我们执行该操作的频率,并在我们得到最终结果前,设置中间状态。这些都是计算属性无法做到的
2、计算属性是基于它们的响应式依赖进行缓存的。只在相关响应式依赖发生改变时它们才会重新求值。