觀察 Watchers
雖然計算屬性在大多數(shù)情況下更合適,但有時也需要一個自定義的 watcher 。這是為什么 Vue 提供一個更通用的方法通過watch 選項,來響應數(shù)據(jù)的變化。當你想要在數(shù)據(jù)變化響應時,執(zhí)行異步操作或開銷較大的操作,這是很有用的。
大家對于 watch 應該不陌生,項目中都用過下面這種寫法:
watch: { someProp () { // do something }}// 或者watch: { someProp: { deep: true, handler () { // do something } }}
上面的寫法告訴 vue,我需要監(jiān)聽 someProp 屬性的變化,于是 vue 在內(nèi)部就會為我們創(chuàng)建一個 watcher 對象。(限于篇幅,我們不聊 watcher 的具體實現(xiàn),感興趣的可以直接看源碼 watcher)
然而在 vue 中,watcher 的功能并沒有這么單一,先上段代碼:
<template> <div> <p>a: {{ a }}</p> <p>b: {{ b }}</p> <button @click="increment">+</button> </div></template><script>export default { data () { return { a: 1 } }, computed: { b () { return this.a * 2 } }, watch: { a () { console.log('a is changed') } }, methods: { increment () { this.a += 1 } }, created () { console.log(this._watchers) }}</script>
上面代碼非常簡單,我們現(xiàn)在主要關(guān)注 created 鉤子中打印的 this._watchers,如下:
分別展開三個 watcher,觀察每一個 expression,從上到下分別為:
b() { return this.a * 2;↵ }"a"function () { vm._update(vm._render(), hydrating);↵ }
上面三個 watcher 代表了三種不同功能的 watcher,我們將其按功能分為三類:
normal-watcher
我們在 watch 中定義的,都屬于這種類型,即只要監(jiān)聽的屬性改變了,都會觸發(fā)定義好的回調(diào)函數(shù)
computed-watcher
每一個 computed 屬性,最后都會生成一個對應的 watcher 對象,但是這類 watcher 有個特點,我們拿上面的 b 舉例:
屬性 b 依賴 a,當 a 改變的時候,b 并不會立即重新計算,只有之后其他地方需要讀取 b 的時候,它才會真正計算,即具備 lazy(懶計算)特性
render-watcher
每一個組件都會有一個 render-watcher, function () {↵ vm._update(vm._render(), hydrating);↵ }
, 當 data/computed
中的屬性改變的時候,會調(diào)用該 render-watcher 來更新組件的視圖
三種 watcher 的執(zhí)行順序
除了功能上的區(qū)別,這三種 watcher 也有固定的執(zhí)行順序,分別是:
computed-render -> normal-watcher -> render-watcher
這樣安排是有原因的,這樣就能盡可能的保證,在更新組件視圖的時候,computed 屬性已經(jīng)是最新值了,如果 render-watcher 排在 computed-render 前面,就會導致頁面更新的時候 computed 值為舊數(shù)據(jù)。
下面從一段實例代碼中看下vue中的watcher
在這個示例中,使用 watch 選項允許我們執(zhí)行異步操作(訪問一個 API),限制我們執(zhí)行該操作的頻率,并在我們得到最終結(jié)果前,設置中間狀態(tài)。這是計算屬性無法做到的。
<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/[email protected]/dist/axios.min.js"></script><script src="https://unpkg.com/[email protected]/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 發(fā)生改變,這個函數(shù)就會運行question: function (newQuestion) {this.answer = 'Waiting for you to stop typing...'this.getAnswer()}},methods: { // _.debounce 是一個通過 lodash 限制操作頻率的函數(shù)。 // 在這個例子中,我們希望限制訪問yesno.wtf/api的頻率 // ajax請求直到用戶輸入完畢才會發(fā)出 // 學習更多關(guān)于 _.debounce function (and its cousin// _.throttle), 參考: https://lodash.com/docs#debouncegetAnswer: _.debounce(function () {var vm = thisif (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})},// 這是我們?yōu)橛脩敉V馆斎氲却暮撩霐?shù)500)}})</script>
小結(jié)
本文并不是源碼解析類文章,只是從一個角度來聊聊,那些看似不相關(guān)的東西(computed/watch/頁面更新),內(nèi)部卻有著緊密的聯(lián)系,希望能拋磚引玉,讓大家更深入的去探索 vue
新聞熱點
疑難解答