對象屬性監聽的兩種方法:
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) } }