watch的作用:監聽vue實例上數據的變動
示例:
1
2
3
4
5
6
|
queryData: { name: '' , creator: '' , selectedStatus: '' , time: [], }, |
1、普通的watch
1
2
3
4
5
6
7
8
9
10
|
data() { return { frontPoints: 0 } }, watch: { frontPoints(newValue, oldValue) { console.log(newValue) } } |
2、數組的watch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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) } } }, deep: true } } |
3、對象的watch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
data() { return { bet: { pokerState: 53, pokerHistory: 'local' } } }, watch: { bet: { handler(newValue, oldValue) { console.log(newValue) }, deep: true } } |
tips: 只要bet中的屬性發生變化(可被監測到的),便會執行handler函數;
如果想監測具體的屬性變化,如pokerHistory變化時,才執行handler函數,則可以利用計算屬性computed做中間層。
事例如下:
4、對象具體屬性的watch[活用computed]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
data() { return { bet: { pokerState: 53, pokerHistory: 'local' } } }, computed: { pokerHistory() { return this .bet.pokerHistory } }, watch: { pokerHistory(newValue, oldValue) { console.log(newValue) } } |
總結
到此這篇關于vue watch監控對象的文章就介紹到這了,更多相關vue watch監控對象內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/web-chuanfa/p/9372459.html