如何對某個物件的屬性進行watch監聽?
阿新 • • 發佈:2018-12-22
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) } }
連結:https://www.jianshu.com/p/d01e145388fc