#### 1. 偵聽器 watch --- Vue 提供了一種更通用的方式來觀察和響應 Vue 實例上的數(shù)據(jù)變動:偵聽屬性 當屬性發(fā)生改變時,自動觸發(fā)屬性對應的偵聽器。 當需要在數(shù)據(jù)變化時執(zhí)行異步或開銷較大的操作時,這個方式是最有用的。 #### 2. 基礎用法 --- **當 msg 屬性的值發(fā)生改變時,就會觸發(fā)偵聽器的執(zhí)行** ```html <div id="app"> <input type="text" v-model="msg"> </div> <script> let vm = new Vue({ el: '#app', data: { msg: 'Hello' }, watch: { msg: function(){ console.log(this.msg) } } }) </script> ``` #### 3. 應用場景:用戶注冊時,驗證用戶名是否存在 --- ```html <div id="app"> 用戶名: <input type="text" name="name" v-model.lazy="username"> <span :style="msgStyle">{{ msg }}</span> <br> 密碼: <input type="password" name="pass"> </div> <script> let vm = new Vue({ el: '#app', data: { msg: '', username: '', msgStyle: '' }, watch: { username: function(){ // 發(fā)送ajax請求 驗證用戶名 if (this.username == 'liang') { this.msg = '該用戶名已存在' this.msgStyle = { color: 'red', fontWeight: 'bold' } } else { this.msg = '用戶名可以注冊' this.msgStyle = { color: 'green', fontWeight: 'bold', } } } } }) </script> ```