看一下演示代碼,先是增加數組和對象。
<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); }