<template>
<div>
{{Obj}}
{{a}}
<button @click="Obj.a=2,a=2">点击改变</button>
</div>
</template>
<script>
export default {
data() {
return {
Obj: {
a: 1,
},
a: 111,
};
},
watch: {
Obj: {
handler: function (newVal, oldVal) {
console.log(newVal, oldVal);
},
deep: true,
},
},
// watch: {
// a: function (newVal, oldVal) {
// console.log(newVal, oldVal);
// },
// },
};
</script>
<style lang="scss" scoped>
</style>
在上述代码中我们可以看到这是我们正常写的深度监听,但是你会发现当你监听简单数据类型的时候可以获取到旧值与新值,但是当我们监听对象的时候就出问题了 问题如下(新值与旧值相同)
这在我们工作中就会遇到一些问题,下面我们解决一下
<template>
<div>
{{Obj}}
{{a}}
<button @click="Obj.a=2,a=2">点击改变</button>
</div>
</template>
<script>
export default {
data() {
return {
Obj: {
a: 1,
},
a: 111,
};
},
computed: {
Obj1() {
return JSON.parse(JSON.stringify(this.Obj));
},
},
watch: {
Obj1: {
deep: true,
handler: function (newVal, oldVal) {
console.log(newVal, oldVal);
},
},
},
// watch: {
// a: function (newVal, oldVal) {
// console.log(newVal, oldVal);
// },
// },
};
</script>
<style lang="scss" scoped>
</style>
如上我们可以看到我们加了一个计算属性,在计算属性中加了一个深拷贝,让后我们监听计算属性的名称就可以了 结果如下
这样就解决了,我们深度监听新值与旧值一样的问题