雖然計算屬性在大多數情況下更合適,但有時也需要一個自定義的偵聽器。這就是為什么 Vue 通過 watch
選項提供了一個更通用的方法,來響應數據的變化。當需要在數據變化時執行異步或開銷較大的操作時,這個方式是最有用的。
例如:
<div id="watch-example"> <p> Ask a yes/no question: <input v-model="question"> </p> <p>{{ answer }}</p> </div>
var watchExampleVM = new Vue({ el: '#watch-example', data: { question: '', answer: 'I cannot give you an answer until you ask a question!'
}, watch: { // 如果 `question` 發生改變,這個函數就會運行 question: function (newQuestion, oldQuestion) { this.answer = 'Waiting for you to stop typing...' this.getAnswer() } }, methods: { // `_.debounce` 是一個通過 Lodash 限制操作頻率的函數。 // 在這個例子中,我們希望限制訪問 yesno.wtf/api 的頻率 // AJAX 請求直到用戶輸入完畢才會發出。想要了解更多關於 // `_.debounce` 函數 (及其近親 `_.throttle`) 的知識, // 請參考:https://lodash.com/docs#debounce getAnswer: _.debounce( function () { if (this.question.indexOf('?') === -1) { this.answer = 'Questions usually contain a question mark. ;-)' return } this.answer = 'Thinking...' var vm = this axios.get('https://yesno.wtf/api') .then(function (response) { vm.answer = _.capitalize(response.data.answer) }) .catch(function (error) { vm.answer = 'Error! Could not reach the API. ' + error }) }, // 這是我們為判定用戶停止輸入等待的毫秒數 500 ) } })
var watchExampleVM = new Vue({ el: '#watch-example', data: { question: '', answer: 'I cannot give you an answer until you ask a question!', childrens: { name: '小強', age: 20, sex: '男' }, tdArray:["1","2"], lastName:"張三" }, watch: { // 如果 `question` 發生改變,這個函數就會運行 question: function (newQuestion, oldQuestion) { this.answer = 'Waiting for you to stop typing...' this.getAnswer() }, childrens:{ handler:function(val,oldval){ console.log(val.name) }, deep:true//對象內部的屬性監聽,也叫深度監聽 }, 'childrens.name':function(val,oldval){ console.log(val+"aaa") },//鍵路徑必須加上引號 lastName:function(val,oldval){ console.log(this.lastName) } }, methods: { // `_.debounce` 是一個通過 Lodash 限制操作頻率的函數。 // 在這個例子中,我們希望限制訪問 yesno.wtf/api 的頻率 // AJAX 請求直到用戶輸入完畢才會發出。想要了解更多關於 // `_.debounce` 函數 (及其近親 `_.throttle`) 的知識, // 請參考:https://lodash.com/docs#debounce getAnswer: _.debounce( function () { if (this.question.indexOf('?') === -1) { this.answer = 'Questions usually contain a question mark. ;-)' return } this.answer = 'Thinking...' var vm = this axios.get('https://yesno.wtf/api') .then(function (response) { vm.answer = _.capitalize(response.data.answer) }) .catch(function (error) { vm.answer = 'Error! Could not reach the API. ' + error }) }, // 這是我們為判定用戶停止輸入等待的毫秒數 500 ) } })