# watch 監聽 (3-3) ###### tags: `Vue`、`3. Options API` 2022.3.3 ### 1. 監聽單一變數 ``` watch:{ 監聽變數名稱(新改變的值,舊有值){ 可撰寫任何動作; } } ``` 範例:密碼設定(條件使用者須設定6位數的密碼,當輸入數值為六位數時,儲存按鈕即可開啟) ``` <input type="text" maxlength="6" placeholder="請輸入六個值" v-model="tmp"><p> <button :disabled="trigger" @click="setpassword">儲存</button> <script> data(){ tmp : '', trigger : true, password : '', }, watch:{ tmp(n,o){ if(n.length==6){ this.trigger = false } else{ this.trigger = true } } }, methods:{ setpassword(){ this.password = this.tmp; alert(`密碼儲存成功!!\n您設定的密碼是:${this.password}`); } } </script> ``` ### 2. Computed 與 Watch 差別 &emsp;&emsp;Computed能較簡單一次監聽多個變數,watch愈要監聽多個變數需要寫多個函式。 ### 範例 ``` <input type="text" v-model="name"><p> <input type="number" v-model.number="name"><p> <input type="checkbox" v-model="vegan"><p> <script> data(){ return{ name:'玉米蛋餅', price: 30, vegan: true, watch_result : '', } }, </script> ``` * Computed : 網頁起始就會觸發值。 ``` {{ com }} <script> computed:{ com(){ return `${this.name} / ${this.price} / ${this.vegan}` } }, </script> ``` * Watch : 需監聽變數有改變,才會觸發。 ``` {{ watch_result }} <script> watch:{ name(){ this.watch_result = `${this.name} / ${this.price} / ${this.vegan}` }, price(){ this.watch_result = `${this.name} / ${this.price} / ${this.vegan}` }, vegan(){ this.watch_result = `${this.name} / ${this.price} / ${this.vegan}` } } </script> ``` ### 3. Watch 深層監聽 (可一次性監聽多個變數,但需要物件型式) ``` watch:{ 物件:{ handler(n,o){ }, deep: true, } } ``` #### 範例 : 讀取產品列表 ``` <input type="text" v-model="product.name"><p> <input type="number" v-model.number="product.price"><p> <input type="checkbox" v-model="product.vegan"><p> {{ watch_result }} <script> data(){ return{ product:{ name:'玉米蛋餅', price: 30, vegan: true, } watch_result : '', } }, watch:{ product:{ handler(){ this.watch_result =`${this.name} / ${this.price} / ${this.vegan}` }, deep: true } }, </script> ```