watch監聽(數組或者對象)

handler:監聽數組或對象的屬性時用到的方法

deep:深度監聽,為了發現對象內部值的變化,可以在選項參數中指定deep:true 。注意監聽數組的變動不需要這么做。

immediate: 在選項參數中指定 immediate: true 將立即以表達式的當前值觸發回調

tips: 只要bet中的屬性發生變化(可被監測到的),便會執行handler函數;如果想監測具體的屬性變化,如pokerHistory變化時,才執行handler函數,則可以利用計算屬性computed做中間層。

1、普通的watch

data() {
 return { frontPoints: 0 }
},
watch: {
 frontPoints(newValue, oldValue) {
 console.log(newValue)
 }
}

2、數組的watch

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)
  }
}

5、watch和computed各自處理的數據關系場景不同

watch擅長處理的場景:一個數據影響多個數據
computed擅長處理的場景:一個數據受多個數據影響

6、method和computed觸發條件不同
computed只提供了緩存的值,而沒有重新計算
只有符合:1.存在依賴型數據 2.依賴型數據發生改變這兩個條件,computed才會重新計算。
而methods下的數據,是每次都會進行計算的

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容