觀察 Watchers
雖然計算屬性在大多數情況下更合適,但有時也需要一個自定義的 watcher 。這是為什么 Vue 提供一個更通用的方法通過watch 選項,來響應數據的變化。當你想要在數據變化響應時,執行異步操作或開銷較大的操作,這是很有用的。
例如:
在這個示例中,使用 watch 選項允許我們執行異步操作(訪問一個 API),限制我們執行該操作的頻率,並在我們得到最終結果前,設置中間狀態。這是計算屬性無法做到的。
<div id="watch-example"> <p> Ask a yes/no question: <input v-model="question"> </p> <p>{{ answer }}</p> </div>
<!-- Since there is already a rich ecosystem of ajax libraries --> <!-- and collections of general-purpose utility methods, Vue core --> <!-- is able to remain small by not reinventing them. This also --> <!-- gives you the freedom to just use what you're familiar with. --> <script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script> <script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script> <script> 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) { this.answer = 'Waiting for you to stop typing...' this.getAnswer() } }, methods: { // _.debounce 是一個通過 lodash 限制操作頻率的函數。 // 在這個例子中,我們希望限制訪問yesno.wtf/api的頻率 // ajax請求直到用戶輸入完畢才會發出 // 學習更多關於 _.debounce function (and its cousin // _.throttle), 參考: https://lodash.com/docs#debounce getAnswer: _.debounce( function () { var vm = this if (this.question.indexOf('?') === -1) { vm.answer = 'Questions usually contain a question mark. ;-)' return } vm.answer = 'Thinking...' 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 ) } }) </script>
