vue (8) Watch 監控變數

watch 操作方法

當watch 監控的變數產生變化時,執行裡頭的 function。

上圖例子: 當trigger被改為true時,觸發 watch裡的function,過3秒後trigger會被改為 false;

一般來說,當我們是要資料連動觸發一個行為,例如打api,等非同步事件時,或呼叫別的函示來處理等,要用watch來處理會比較好。

watch 範例:

當 w 資料改變時,觸發computed裡的 width,當width有改變時,會被watch監聽,而去處發一個行為,也就是updateCanvas()

watch 監測物件

我們可以對單一變數進行觀測,也可以觀測物件裡的值。

  1. 觀測單一變數時,直接寫變數名稱:

    參數裡 val代表新的值,oldVal代表舊的值

  2. 觀測物件裡的單一值時,要用 [‘obj.num’] 取得物件裡的值做觀測,當值改

    變時,就執行函式裡的內容。

  3. 要觀察整個物件時,要用下圖最後一種寫法,handler就是要執行的函示,

    deep:true,代表我要觀察得很深,就是整包物件。

  1. 要觀察陣列裡物件時,也要使用deep的方式。

watch 和 computed 不同

  • Watch
    監聽單一 “變數” 觸發事件,該函式可同時操作多個變數

  • Computed
    監聽多個變數觸發事件,會產生一個值

1
2
3
4
5
6
7
8
9
10
11
12
13
// 例子:監聽單一變數並更新多個變數
watch: {
productName() {
this.result3 = `媽媽買了 ${this.productName},總共花費 ${this.productPrice} 元,另外這 ${this.productVegan ? '是' : '不是'} 素食的`;
},
productPrice() {
this.result3 = `媽媽買了 ${this.productName},總共花費 ${this.productPrice} 元,另外這 ${this.productVegan ? '是' : '不是'} 素食的`;
},
productVegan() {
this.result3 = `媽媽買了 ${this.productName},總共花費 ${this.productPrice} 元,另外這 ${this.productVegan ? '是' : '不是'} 素食的`;
},
}
// 分別監聽 productName、productPrice、productVegan 來產生結果
1
2
3
4
5
6
7

computed: {
result2() {
return `媽媽買了 ${this.productName},總共花費 ${this.productPrice} 元,另外這 ${this.productVegan ? '是' : '不是'} 素食的`;
}
},
// 同時監聽 productName、productPrice、productVegan 來產生結果