vue中提供了$watch的方法來作對象變化的監聽,並且在callback中會返回兩個對象,分別是oldValue和newValue.
顧名思義,這兩個對象就是對象發生變化先後的值。
可是在使用過程當中我發現這兩個值並不老是預期的。html
定義data的值vue
data: { arr: [{ name: '笨笨', address: '上海' }, { name: '笨笨熊', address: '北京' }], obj: { name: '呆呆', address: '蘇州' }, str: '哈哈哈' }
定義watchgit
watch: { arr: function(newValue, oldValue) { console.log(newValue, oldValue) console.log(JSON.stringify(oldValue) === JSON.stringify(newValue)) }, obj: function(newValue, oldValue) { console.log(newValue, oldValue) console.log(JSON.stringify(oldValue) === JSON.stringify(newValue)) }, str: function(newValue, oldValue) { console.log(newValue, oldValue) console.log(JSON.stringify(oldValue) === JSON.stringify(newValue)) }, }
定義事件觸發github
methods: { test() { this.arr.push({ name: 9 }) this.$set(this.obj, 'i', 0) this.str = '' }, test1() { this.arr = [{ name: '000' }] this.obj = { name: 999 } this.str = '123' } }
測試結果爲segmentfault
對數組進行push操做和對Obj進行$set操做,雖然均可能觸發watch事件,可是在callback返回的結果中,oldValue和newValue相同。字符串對象如預期返回數組
在對數組和Obj統一進行賦值操做時,watch觸發而且oldValue和newValue如預期返回測試
關於watch的其餘測試能夠參考我以前的文章
vue中正確的使用watch進行監聽this
測試地址(測試時請打開控制檯)
https://zuank.github.io/notes...code