雖然計算屬性在大多數(shù)情況下更合適,但有時也需要一個自定義的 watcher 。這是為什么 Vue 提供一個更通用的方法通過watch 選項,來響應數(shù)據(jù)的變化。當你想要在數(shù)據(jù)變化響應時,執(zhí)行異步操作或開銷較大的操作,這是很有用的。本文主要介紹了vue 中的 watcher的相關資料,需要的朋友可以參考下,希望能幫助到大家。
大家對于 watch 應該不陌生,項目中都用過下面這種寫法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 的功能并沒有這么單一,先上段代碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <template> <p> <p>a: {{ a }}</p> <p>b: {{ b }}</p> <button @click="increment">+</button> </p> </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> |
在線demo
上面代碼非常簡單,我們現(xiàn)在主要關注 created 鉤子中打印的 this._watchers,如下:
分別展開三個 watcher,觀察每一個 expression,從上到下分別為:
1 2 3 | b() { return this.a * 2;? } "a" function () { vm._update(vm._render(), hydrating);? } |
上面三個 watcher 代表了三種不同功能的 watcher,我們將其按功能分為三類:
在 watch 中定義的,用于監(jiān)聽屬性變化的 watcher (第二個)
用于 computed 屬性的 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í)行順序,分別是:
1 | computed-render -> normal-watcher -> render-watcher |
這樣安排是有原因的,這樣就能盡可能的保證,在更新組件視圖的時候,computed 屬性已經(jīng)是最新值了,如果 render-watcher 排在 computed-render 前面,就會導致頁面更新的時候 computed 值為舊數(shù)據(jù)。
下面從一段實例代碼中看下vue中的watcher
在這個示例中,使用 watch 選項允許我們執(zhí)行異步操作(訪問一個 API),限制我們執(zhí)行該操作的頻率,并在我們得到最終結果前,設置中間狀態(tài)。這是計算屬性無法做到的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | <p id="watch-example"> <p> Ask a yes/no question: <input v-model="question"> </p> <p>{{ answer }}</p> </p> <!-- 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 發(fā)生改變,這個函數(shù)就會運行 question: function (newQuestion) { this.answer = 'Waiting for you to stop typing...' this.getAnswer() } }, methods: { // _.debounce 是一個通過 lodash 限制操作頻率的函數(shù)。 // 在這個例子中,我們希望限制訪問yesno.wtf/api的頻率 // ajax請求直到用戶輸入完畢才會發(fā)出 // 學習更多關于 _.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 }) }, // 這是我們?yōu)橛脩敉V馆斎氲却暮撩霐?shù) 500 ) } }) </script> |
/* @flow */ import { queueWatcher } from './scheduler' import Dep, { pushTarget, popTarget } from './dep' import { warn, remove, isObject, parsePath, _Set as Set, handleError } from '../util/index' let uid = 0 /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. 一個 watcher編譯成 一個表達式 和 依賴集合, 還能出發(fā)回調(diào)當 v-model的值改變 這也能用到wathcer api中, 如果 vm.$watch('abc', fn); */ export default class Watcher { vm: Component; expression: string; cb: Function; id: number; deep: boolean; user: boolean; lazy: boolean; sync: boolean; dirty: boolean; active: boolean; deps: Array<Dep>; newDeps: Array<Dep>; depIds: Set; newDepIds: Set; getter: Function; value: any; constructor ( vm: Component, expOrFn: string | Function, cb: Function, options?: Object ) { //這個watcher所屬的vm this.vm = vm // 一個vm 有多個watchers , vm.$watch(a,fn1) vm.$watch(b,fn2) {{b.UpperCase()}} 等等 vm._watchers.push(this) // options if (options) { //是否深度檢測依賴 this.deep = !!options.deep this.user = !!options.user this.lazy = !!options.lazy this.sync = !!options.sync } else { this.deep = this.user = this.lazy = this.sync = false } this.cb = cb this.id = ++uid // uid for batching this.active = true this.dirty = this.lazy // for lazy watchers this.deps = [] this.newDeps = [] this.depIds = new Set() this.newDepIds = new Set() this.expression = process.env.NODE_ENV !== 'production' ? expOrFn.toString() : '' // parse expression for getter if (typeof expOrFn === 'function') { //監(jiān)控函數(shù) this.getter = expOrFn } else { //監(jiān)控表達式, 注意 這里也會返回一個路徑的函數(shù) this.getter = parsePath(expOrFn) if (!this.getter) { this.getter = function () {} process.env.NODE_ENV !== 'production' && warn( `Failed watching path: "${expOrFn}" ` + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ) } } this.value = this.lazy ? undefined : this.get() } /** * Evaluate the getter, and re-collect dependencies. */ get () { //Dep.target = this pushTarget(this) let value const vm = this.vm if (this.user) { try { // 因為傳入了 vm, 所以在methods中可以取得this.data.abc // 比如 this.getter 是 fucntion(){ return this.price * this.nums; }; 因為執(zhí)行這個函數(shù), 也就會去獲取 this.price 和 this.nums的值 // 就會分別觸發(fā)這兩個數(shù)據(jù)的get方法, 然后這個watcher就會加入這兩個數(shù)據(jù)的dep, this.push(depq) this.push(dep2); 通過這一步就收集了這個函數(shù)的兩個依賴 value = this.getter.call(vm, vm) } catch (e) { handleError(e, vm, `getter for watcher "${this.expression}"`) } } else { value = this.getter.call(vm, vm) } // "touch" every property so they are all tracked as // dependencies for deep watching //“觸摸”每一個屬性,這樣它們都被跟蹤為 深度觀察依賴 if (this.deep) { traverse(value) } popTarget() this.cleanupDeps() return value } /** * Add a dependency to this directive. 添加一個依賴到這個指令 */ addDep (dep: Dep) { const id = dep.id if (!this.newDepIds.has(id)) { this.newDepIds.add(id) this.newDeps.push(dep) if (!this.depIds.has(id)) { dep.addSub(this) } } } /** * Clean up for dependency collection. */ cleanupDeps () { let i = this.deps.length while (i--) { const dep = this.deps[i] if (!this.newDepIds.has(dep.id)) { dep.removeSub(this) } } let tmp = this.depIds this.depIds = this.newDepIds this.newDepIds = tmp this.newDepIds.clear() tmp = this.deps this.deps = this.newDeps this.newDeps = tmp this.newDeps.length = 0 } /** * Subscriber interface. * Will be called when a dependency changes. */ update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true } else if (this.sync) { this.run() } else { queueWatcher(this) } } /** * Scheduler job interface. * Will be called by the scheduler. */ run () { if (this.active) { const value = this.get() if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value const oldValue = this.value this.value = value if (this.user) { try { this.cb.call(this.vm, value, oldValue) } catch (e) { handleError(e, this.vm, `callback for watcher "${this.expression}"`) } } else { this.cb.call(this.vm, value, oldValue) } } } } /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. 計算一個watcher的值, 這個只會被 延遲watchers調(diào)用 */ evaluate () { this.value = this.get() this.dirty = false } /** * Depend on all deps collected by this watcher. 通過這個watcher, 收集所有的依賴? */ depend () { let i = this.deps.length while (i--) { this.deps[i].depend() } } /** * Remove self from all dependencies' subscriber list. 從所有的依賴訂閱清單中移除自己 */ teardown () { if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed. // 移除依賴是一個昂貴的操作, 所有如果這個vm已經(jīng)銷毀le, 我們就跳一跳 if (!this.vm._isBeingDestroyed) { remove(this.vm._watchers, this) } let i = this.deps.length while (i--) { this.deps[i].removeSub(this) } this.active = false } } } /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. 遞歸追蹤一個對象去喚起所有的已經(jīng)轉(zhuǎn)換的getters, 這樣在一個對象的所以嵌套的熟悉都被收集成為一個深層的依賴 */ const seenObjects = new Set() function traverse (val: any) { seenObjects.clear() _traverse(val, seenObjects) } function _traverse (val: any, seen: Set) { let i, keys const isA = Array.isArray(val) if ((!isA && !isObject(val)) || !Object.isExtensible(val)) { return } if (val.__ob__) { const depId = val.__ob__.dep.id if (seen.has(depId)) { return } seen.add(depId) } if (isA) { i = val.length while (i--) _traverse(val[i], seen) } else { //for in 都不用了, 加快速度 keys = Object.keys(val) i = keys.length while (i--) _traverse(val[keys[i]], seen) } }
如對本文有疑問,請?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會為你解答??! 點擊進入論壇