解决的方法有两种:
方式1:通过计算属性
方式2:通过$watch完成监控
方式1:计算属性(computed):
data() {
return {
num1: 10,
num2: 20,
num3: 30,
num4: 40,
msg: "msg",
}
},
computed: {
sum() {
return this.num1 + this.num2
}
},
watch: {
sum(nv, ov) {
console.log("num1+num2求和结果变化:", nv, ov);
}
},
方式2:($watch):
data() {
return {
num1: 10,
num2: 20,
num3: 30,
num4: 40,
msg: "msg",
}
},
computed: {
sum() {
return this.num1 + this.num2
}
},
watch: {
sum(nv, ov) {
console.log("num1+num2求和结果变化:", nv, ov);
}
},
methods: {
addWatch() {
// 在应用根属性上添加一个用于中转,但不需要劫持的变量数据 - 为其他区域提供调用支持
// 这种中转数据变量 在vue 开发规范中建议 以 $ 开头,实现和普通劫持变量的区分
if(this.$unwatch) return;
this.$unwatch = this.$watch("msg", (nv, ov) => {
console.log("$watch 监控的msg发生变化", nv, ov);
})
console.log(this.$unwatch);
console.log(this);
},
removeWatch(){
if(!this.$unwatch) return;
this.$unwatch();
this.$unwatch = undefined;
},
addNumWatch() {
this.$watch(
() => {
// return this.num3+this.num4
// return [this.num3,this.num4]
return {
num3:this.num3,
num4:this.num4
}
},
(nv, ov) => {
// console.log("$watch 监控的num3+num4发生变化", nv, ov);
// console.log("$watch 监控的[num3,num4]发生变化", nv, ov);
console.log("$watch 监控的{num3,num4}发生变化", nv, ov);
}
)
}