watch監聽(數組或者對象)


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

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

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

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

 

1、普通的watch
按 Ctrl+C 復制代碼

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


按 Ctrl+C 復制代碼
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下的數據,是每次都會進行計算的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM