vue的watch


對象屬性監聽的兩種方法:

1.普通的watch

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

2.對象屬性的watch

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

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

3.對象具體屬性的watch

復制代碼
data() {
  return {
    bet: {
      pokerState: 53,
      pokerHistory: 'local'
    }   
    }
},
computed: {
  pokerHistory() {
    return this.bet.pokerHistory
  }
},
watch: {
  pokerHistory(newValue, oldValue) {
    console.log(newValue)
  }
}
復制代碼

對象具體屬性的watch可以直接用引號把屬性括起來,就可以實現對象中特定屬性的監聽事件:

復制代碼
data() {
  return {
    bet: {
      pokerState: 53,
      pokerHistory: 'local'
    }   
    }
},
watch: {
  'bet.pokerHistory'(newValue, oldValue) {
    console.log(newValue)
  }
}


免責聲明!

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



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