看一下演示代码,先是增加数组和对象。
<template>
<div>
<p>这是我定义的数组</p>
<div>{{this.arr}}</div>
<button @click="changeArr">点击这里我就要修改数组里第一个</button>
<p>这是我的对象</p>
<div>{{this.haha}}</div>
<button @click="changeObj">点击这里我就要添加对象的属性</button>
</div>
</template>
<script>
export default {
name: "test",
data() {
return {
arr: [0, 1, 2, 3, 4, 5, 6],
haha: {
name: "123",
age: 12,
story: "从前有座山",
}
};
},
watch:{
'arr':{
handler:function(val,oldval){
console.log('修改后',val,'修改前',oldval);
},
},
'haha':{
handler:function(val,oldval){
console.log('修改后',val,'修改前',oldval);
}
}
},
methods: {
changeArr() {
this.arr.push('12332') // 添加数组
console.log("这是修改之后的数组", this.arr);
},
changeObj() {
this.haha.content = "我是一个小和尚"; // 添加对象
console.log("这是修改之后的对象", this.haha);
}
}
};
</script>
控制台输出

由此可见,watch监听到了数组的增加,并没有监听到对象的增加(没有监听到所以视图中的数据并没有发生改变)

接下来修改数组和对象(修改了对象中的value)
changeArr() {
this.arr[0]=1232 // 修改数组
console.log("这是修改之后的数组", this.arr);
},
changeObj() {
this.haha.story = "我是一个小和尚"; // 修改对象的value
console.log("这是修改之后的对象", this.haha);
}

watch是监听不到的,解决方法:
惊!VUE居然数据不能驱动视图?$set详细教程
网友评论