handler:監聽數組或對象的屬性時用到的方法
deep:深度監聽,為了發現對象內部值的變化,可以在選項參數中指定 deep:true 。注意監聽數組的變動不需要這么做。
immediate: 在選項參數中指定 immediate: true 將立即以表達式的當前值觸發回調
tips: 只要bet中的屬性發生變化(可被監測到的),便會執行handler函數;如果想監測具體的屬性變化,如pokerHistory變化時,才執行handler函數,則可以利用計算屬性computed做中間層。
data() { return {
frontPoints: 0
} }, watch: { frontPoints(newValue, oldValue) { console.log(newValue) } }
data() { return { winChips: new Array(11).fill(0) } }, watch: { winChips: { handler(newValue, oldValue) { for (let i = 0; i < newValue.length; i++) { if (oldValue[i] != newValue[i]) { console.log(newValue) } } }, } }
3、對象的watch
data() { return { bet: { pokerState: 53, pokerHistory: 'local' } } }, watch: { bet: { handler(newValue, oldValue) { console.log(newValue) }, deep: true } }
4、對象具體屬性的watch[活用computed]
data() { return { bet: { pokerState: 53, pokerHistory: 'local' } } }, computed: { pokerHistory() { return this.bet.pokerHistory } }, watch: { pokerHistory(newValue, oldValue) { console.log(newValue) } }
watch擅長處理的場景:一個數據影響多個數據
computed擅長處理的場景:一個數據受多個數據影響
6、method和computed觸發條件不同
computed只提供了緩存的值,而沒有重新計算
只有符合:1.存在依賴型數據 2.依賴型數據發生改變這兩個條件,computed才會重新計算。
而methods下的數據,是每次都會進行計算的
作者:乖乖果效36
鏈接:https://www.jianshu.com/p/29dc0c079949