vue watch 監聽

一、普通的watchjavascript

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

 

二、數組的watch,注意監聽數組的變更不須要deep: true 。java

複製代碼
data() {
    return {
        winChips: new Array(11).fill(0)   
    }
},
watch: {
  winChips(newValue, oldValue) {
    for (let i = 0; i < newValue.length; i++) {
      if (oldValue[i] != newValue[i]) {
        console.log(newValue)
      }
    }
  }
}
複製代碼

fill方法使用給定值,填充一個數組。數組

['a', 'b', 'c'].fill(7)  
// [7, 7, 7]  
new Array(3).fill(7)  
// [7, 7, 7]  
['a', 'b', 'c'].fill(7, 1, 2)  
// ['a', 7, 'c']  

上面代碼代表,fill方法用於空數組的初始化很是方便。數組中已有的元素,會被所有抹去。 函數

 

三、對象的watchpost

複製代碼
data() {
  return {
    bet: {
      pokerState: 53,
      pokerHistory: 'local'
    } } }, watch: {   bet: {
    handler(newValue, oldValue) {
      console.log(newValue)
    },
    deep: true
  }
}
複製代碼



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

 四、對象具體屬性的watch[活用computed]this

複製代碼
data() {
  return {
    bet: {
      pokerState: 53,
      pokerHistory: 'local'
    } } },
computed: {
  pokerHistory() {
    return this.bet.pokerHistory
  }
}, watch: {   pokerHistory(newValue, oldValue) {
    console.log(newValue)
  }
}
複製代碼
相關文章
相關標籤/搜索