Vue?響應(yīng)式系統(tǒng)依賴收集過程原理解析
背景
在 Vue 的初始化階段,_init 方法執(zhí)行的時候,會執(zhí)行 initState(vm) ,它的定義在 src/core/instance/state.js 中。在初始化 data 和 props option 時我們注意 initProps 和 initData 方法中都調(diào)用了 observe 方法。通過 observe (value),就可以將數(shù)據(jù)變成響應(yīng)式。
export function initState (vm: Component) { vm._watchers = [] const opts = vm.$options if (opts.props) initProps(vm, opts.props) if (opts.methods) initMethods(vm, opts.methods) if (opts.data) { initData(vm) } else { observe(vm._data = {}, true /* asRootData */) } if (opts.computed) initComputed(vm, opts.computed) if (opts.watch && opts.watch !== nativeWatch) { initWatch(vm, opts.watch) } }
initProps
if (value === undefined) { observe(value); }
initData
observe(data, true /* asRootData */)
目標(biāo)
- 理解 Vue 數(shù)據(jù)響應(yīng)式原理,了解響應(yīng)式原理依賴收集的過程
- 了解在什么階段會觸發(fā)依賴收集
源碼解讀
入口函數(shù):observe
observe 方法定義在 src/core/observer/index.js 中。如果是一個非 VNode 的對象類型的數(shù)據(jù),它會嘗試給這個值去創(chuàng)建一個 observer 實例,如果創(chuàng)建成功,返回新的 observer?;蛘呷绻?ob 已經(jīng)存在了,就會直接返回一個現(xiàn)有的 observer。
/** * 嘗試給這個值去創(chuàng)建一個 observer 實例,如果創(chuàng)建成功,返回新的 observer * 或者如果值已經(jīng)有了,返回一個現(xiàn)有的 observer * @param {*} value * @param {boolean} asRootData * @returns Observer | void */ export function observe (value: any, asRootData: ?boolean): Observer | void { if (!isObject(value) || value instanceof VNode) { return } let ob: Observer | void // 如果 value 已經(jīng)有 observer,就返回現(xiàn)有的 observer // 否則如果不是服務(wù)器渲染,value是數(shù)組或者對象,value 是可擴展的,value 不是 vue 實例,就創(chuàng)建一個新的 observer if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__ } else if ( shouldObserve && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value) } // 如果是根組件,vmCount 不為0 if (asRootData && ob) { ob.vmCount++ } return ob }
通過 new Observer(value) 可以給 value 創(chuàng)建一個 observer 實例,那么 Observer 類的定義和作用是什么?在同一個文件下可以看到 class Observer 是如何定義的。
class Observer
Observer 方法定義在 src/core/observer/index.js 中。在它的構(gòu)造函數(shù)中,首先實例化 Dep 對象(主要用來存放它的 watcher列表),接著通過執(zhí)行 def 函數(shù)把自身實例添加到數(shù)據(jù)對象 value 的 ob 屬性上,所以存在 ob 屬性意味著已經(jīng)被觀察過。最后判斷 value 為數(shù)組的情況下,會數(shù)組項遍歷,給數(shù)組的每一項創(chuàng)建一個 observe 實例;如果是對象,那么遍歷所有的屬性,通過Object.defineProperty修改getter/setters。
/** * Observer 類和每個響應(yīng)式對象關(guān)聯(lián)。 * observer 會轉(zhuǎn)化對象的屬性值的 getter/setters 方法收集依賴和派發(fā)更新。 */ export class Observer { value: any; dep: Dep; vmCount: number; // number of vms that have this object as root $data constructor(value: any) { this.value = value this.dep = new Dep() // 存放 Observer 的 watcher 列表 this.vmCount = 0 def(value, '__ob__', this) // __ob__ 指向自身 observe 實例,存在 __ob__ 屬性意味著已經(jīng)被觀察過 // 如果是數(shù)組 if (Array.isArray(value)) { // hasProto = '__proto__' in {} 判斷對象是否存在 __proto__ 屬性 if (hasProto) { // 如果有 __proto__,就將 value.__proto__ 指向 arrayMethods protoAugment(value, arrayMethods) } else { // 否則,就遍歷 arrayMethods,將值復(fù)制到 value 上 copyAugment(value, arrayMethods, arrayKeys) } this.observeArray(value) // 數(shù)組項遍歷,給數(shù)組的每一項創(chuàng)建一個 observe 實例 } else { this.walk(value) // 遍歷所有的屬性,修改 getter/setters } } // 遍歷所有的屬性,修改 getter/setters,這個方法只有在 value 是object時調(diào)用 walk (obj: Object) { const keys = Object.keys(obj) for (let i = 0; i < keys.length; i++) { defineReactive(obj, keys[i]) } } // 數(shù)組項遍歷,給數(shù)組的每一項創(chuàng)建一個 observe 實例 observeArray (items: Array<any>) { for (let i = 0, l = items.length; i < l; i++) { observe(items[i]) } } }
我們來看看對于數(shù)組和對象, Observe 分別做了什么處理。
Observe 如何處理數(shù)組
首先,對于 value 為數(shù)組而言,由于 proto 不是標(biāo)準(zhǔn)屬性,有些瀏覽器不支持,比如 IE6-10,Opera10.1,所以需要根據(jù)對象是否存在 proto 屬性區(qū)分在原型鏈上添加方法, protoAugment 和 copyAugment 都是在目標(biāo)對象上添加屬性值。
/** * 將 target.__proto__ 指向 src * 攔截原型鏈__proto__,來增強目標(biāo)對象或數(shù)組 * @param {*} target * @param {Object} src */ function protoAugment (target, src: Object) { /* eslint-disable no-proto */ target.__proto__ = src /* eslint-enable no-proto */ } /** * 遍歷 key 屬性值列表,將 src 中的 key 屬性值逐一定義到 target 的屬性中 * 通過定義隱藏屬性,來增強目標(biāo)對象或數(shù)組 * @param {Object} target * @param {Object} src * @param {Array<string>} keys */ /* istanbul ignore next */ function copyAugment (target: Object, src: Object, keys: Array<string>) { for (let i = 0, l = keys.length; i < l; i++) { const key = keys[i] def(target, key, src[key]) // // 為 target 定義 key 和值 } }
在原型鏈上添加的屬性方法 arrayMethods 在 src/core/observer/array.js 可以找到他的定義。實際上 arrayMethods 就是 push pop shift unshift splice sort reverse 七個個方法。這么做的目的是因為要通過 proto 操作數(shù)據(jù)的原型鏈,覆蓋數(shù)組默認(rèn)的七個原型方法,以實現(xiàn)數(shù)組響應(yīng)式。
Observe 如何處理對象
其次,對于對象而言,會去遍歷對象的每個 key,調(diào)用 defineReactive(obj, keys[i]) 方法。它會為 obj[key] 創(chuàng)建一個依賴類 dep(會幫這個key 定義一個 id 和 subs(watcher 訂閱者列表) 方便依賴收集)然后再利用 Object.defineProperty 對對象的 get 和 set 方法做了處理。get 攔截對 obj[key] 的讀取操作,set 攔截對 obj[key] 的寫操作。
/** * 在對象上定義一個響應(yīng)式的屬性。 * @param {Object} obj * @param {string} key * @param {*} val * @param {*} customSetter * @param {*} shallow * @returns */ export function defineReactive ( obj: Object, key: string, val: any, customSetter?: ?Function, shallow?: boolean ) { const dep = new Dep() // 為 Object 的 key 創(chuàng)建一個依賴類,會幫這個key 定義一個 id 和 subs(watcher 訂閱者列表) const property = Object.getOwnPropertyDescriptor(obj, key) // 獲取 obj[key] 的屬性描述符,發(fā)現(xiàn)它是不可配置對象的話直接 return if (property && property.configurable === false) { return } // cater for pre-defined getter/setters const getter = property && property.get const setter = property && property.set if ((!getter || setter) && arguments.length === 2) { val = obj[key] } // 對 obj[key] 進(jìn)行觀察,保證對象中的所有 key 都被觀察 let childOb = !shallow && observe(val) Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { const value = getter ? getter.call(obj) : val if (Dep.target) { dep.depend() if (childOb) { childOb.dep.depend() if (Array.isArray(value)) { dependArray(value) } } } return value }, set: function reactiveSetter (newVal) { // 舊的 obj[key] const value = getter ? getter.call(obj) : val // 如果新老值一樣,則直接 return,不跟新更不觸發(fā)響應(yīng)式更新過程 /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (process.env.NODE_ENV !== 'production' && customSetter) { customSetter() } // setter 不存在說明該屬性是一個只讀屬性,直接 return // #7981: for accessor properties without setter if (getter && !setter) return // 設(shè)置新值 if (setter) { setter.call(obj, newVal) } else { val = newVal } // 對新值進(jìn)行觀察,讓新值也是響應(yīng)式的 childOb = !shallow && observe(newVal) dep.notify() // 通知依賴的觀察者更新 } }) }
可以看到,defineReactive(obj, keys[i]) 中對對象做了處理,不論嵌套的多深,都會 observe(value) 繼續(xù)觀察,在設(shè)置了新的值后,也會重新對新值進(jìn)行觀察,讓新值也是響應(yīng)式的。
上面的代碼中,在 Observer 類構(gòu)造函數(shù)執(zhí)行時創(chuàng)建了一個 new Dep(),之后在定義對象的響應(yīng)式屬性時,也為 Object 的 key 創(chuàng)建一個依賴類 const dep = new Dep(),然后在 set 數(shù)據(jù)值會觸發(fā) dep.notify()。那么 Dep 的作用是什么呢?
class Dep
Dep 類的定義在 src/core/observer/dep.js 下。它的構(gòu)造函數(shù)中定義了 id 和一個用于儲存訂閱這個 dep 的 watcher 的數(shù)組 subs[]。
/** * 一個 dep 對應(yīng)一個 object.key,每次 key 更新時調(diào)用 dep.notify(), * dep 下的 subs 存放 Watcher 列表,可以調(diào)用 dep.notify() 觸發(fā) watcher.update() 使 Watcher 列表更新。 */ export default class Dep { static target: ?Watcher; // Dep 類的靜態(tài)屬性,可以使用 Dep.target 訪問,內(nèi)容是 Watcher id: number; subs: Array<Watcher>; // Watcher 組成的訂閱列表 constructor() { this.id = uid++ this.subs = [] // watcher 訂閱者列表 } // 向訂閱者列表中添加一個訂閱者 Watcher addSub (sub: Watcher) { this.subs.push(sub) } // 從訂閱者列表中刪掉一個 Watcher removeSub (sub: Watcher) { remove(this.subs, sub) } // 讓全局唯一的 watcher 添加當(dāng)前的依賴 depend () { if (Dep.target) { Dep.target.addDep(this) } } // 通知訂閱者列表觸發(fā)更新 notify () { // 用 slice() 方法拷貝一個 subs,不影響 this.subs const subs = this.subs.slice() if (process.env.NODE_ENV !== 'production' && !config.async) { // 如果不是運行異步,Watcher 列表不會在調(diào)度器中排序,我們需要去對他們進(jìn)行排序以確保他們按順序正確的調(diào)度 subs.sort((a, b) => a.id - b.id) } // 依次觸發(fā) Watcher.update() for (let i = 0, l = subs.length; i < l; i++) { subs[i].update() } } }
Dep.target
這里的 Dep.target 就是一個 watcher實例,在依賴收集時會調(diào)用 watcher.addDep(this) 向觀察者中添加自己這個依賴。 Dep.notify() 會通知這個依賴的觀察者們依次觸發(fā) Watcher.update()。
Dep.target 是當(dāng)前正在執(zhí)行的 watcher,同一時間只會有一個 watcher 在執(zhí)行。
Dep.target = null const targetStack = [] // 在需要進(jìn)行依賴收集的時候調(diào)用,設(shè)置 Dep.target = watcher export function pushTarget (target: ?Watcher) { targetStack.push(target) Dep.target = target } // 依賴收集結(jié)束調(diào)用,設(shè)置 Dep.target 為對堆棧中前一個 watcher export function popTarget () { targetStack.pop() Dep.target = targetStack[targetStack.length - 1] }
class Watcher
Watcher類定義在 src/core/observer/watcher.js 中。一個組件渲染時創(chuàng)建一個 watcher。
或者一個表達(dá)式創(chuàng)建一個 Watcher ,當(dāng)表達(dá)式發(fā)生改變時觸發(fā)調(diào)度。
Watcher 的原型方法中和依賴收集相關(guān)的方法有 get() addDep() cleanupDep()等。在 watcher 的構(gòu)造函數(shù)中會調(diào)用它的原型方法 get(),它將 Dep.target 指向當(dāng)前 watcher。
/** * Watcher 解析一個表達(dá)式,收集依賴,當(dāng)表達(dá)式發(fā)生改變時觸發(fā)調(diào)度。Watcher 類用于 $watch() api 和指令。 */ 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>; // deps 表示上一次添加的 Dep 實例數(shù)組 newDeps: Array<Dep>; // newDeps 表示新添加的 Dep 實例數(shù)組 depIds: SimpleSet; newDepIds: SimpleSet; before: ?Function; getter: Function; value: any; constructor( // 類實例化時傳入的參數(shù)會用作構(gòu)造函數(shù)的參數(shù) vm: Component, expOrFn: string | Function, cb: Function, options?: ?Object, isRenderWatcher?: boolean ) { this.vm = vm if (isRenderWatcher) { vm._watcher = this } vm._watchers.push(this) // options if (options) { this.deep = !!options.deep this.user = !!options.user this.lazy = !!options.lazy this.sync = !!options.sync this.before = options.before } 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') { this.getter = expOrFn } else { this.getter = parsePath(expOrFn) if (!this.getter) { this.getter = noop 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() } // 一些原型方法 // 以下是定義在 watcher 類原型對象上的方法,用 Watcher.prototype.get() 訪問 /** * Evaluate the getter, and re-collect dependencies. */ get () { // 將 Dep.target 指向當(dāng)前 watcher pushTarget(this) let value const vm = this.vm try { // 讓 vm 調(diào)用 this.getter,并傳入 vm 作為參數(shù) // this.getter = expOrFn value = this.getter.call(vm, vm) } catch (e) { if (this.user) { handleError(e, vm, `getter for watcher "${this.expression}"`) } else { throw e } } finally { // 如果需要監(jiān)聽對象內(nèi)部值的變化,那么調(diào)用 traverse 方法 if (this.deep) { traverse(value) // 遞歸遍歷 value 的每個屬性, 確保每個屬性都被監(jiān)聽 } // 當(dāng)前 vm 的數(shù)據(jù)依賴收集已經(jīng)完成,恢復(fù) Dep.target popTarget() this.cleanupDeps() } return value } /** * Add a dependency to this directive. * 添加一個依賴:如果dep數(shù)組中沒有dep.id,那么觸發(fā) dep 訂閱當(dāng)前 watcher */ 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 () { // 先保持 deps 和 newDepIds數(shù)量相同 let i = this.deps.length while (i--) { const dep = this.deps[i] if (!this.newDepIds.has(dep.id)) { dep.removeSub(this) // 如果當(dāng)前 dep 中沒有 newDepIds,就移除它的訂閱者列表 } } // 更新 depIds、deps 為當(dāng)前的 deps,然后清除 newDepIds 和 newDeps 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. */ // 訂閱者接口,當(dāng)依賴改變時將會被調(diào)用 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. */ // 調(diào)度器工作接口,將會被調(diào)度器調(diào)用 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) { const info = `callback for watcher "${this.expression}"` invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info) } else { this.cb.call(this.vm, value, oldValue) } } } } /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ evaluate () { this.value = this.get() this.dirty = false } /** * Depend on all deps collected by this watcher. */ depend () { let i = this.deps.length while (i--) { this.deps[i].depend() } } /** * Remove self from all dependencies' subscriber list. * 從所有依賴項的訂閱者列表中刪除 self */ 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. // 如果組件不是正在被銷毀 if (!this.vm._isBeingDestroyed) { remove(this.vm._watchers, this) // 從數(shù)組中刪除一個項目。 } let i = this.deps.length while (i--) { this.deps[i].removeSub(this) } this.active = false } } }
上面的流程是在 Vue 初始化時對數(shù)據(jù)做的處理,調(diào)用創(chuàng)建了 observe 實例和 dep 實例。但是并沒有提到 watcher 實例是在什么時候創(chuàng)建的。我們先來看看一些使用 Watcher 的地方。
Watcher 的應(yīng)用
- beforeMount
在 beforeMount 生命周期時,會通過 new Watcher 生成一個渲染 Watcher,它會在頁面渲染的過程中訪問每個數(shù)據(jù)對象的 getter 屬性,從而進(jìn)行依賴的收集。 - initComputed()
遍歷 computed 中的每個 key,向 computed watcher 列表中新增一個 watcher 實例。 - initWatch()
遍歷 watch 中的每一個 key,調(diào)用 vm.$watch 創(chuàng)建一個 watcher 實例。
何時觸發(fā)依賴收集?
在 src/core/instance/lifecycle.js 中可以看到,在 beforeMount 階段實例化了一個 render watcher,并傳入一個 updateComponent 的 expOrFn 方法。之后 watcher 調(diào)用它的 this.get()。\
callHook(vm, 'beforeMount') updateComponent = () => { vm._update(vm._render(), hydrating) } new Watcher(vm, updateComponent, noop, { before () { if (vm._isMounted && !vm._isDestroyed) { callHook(vm, 'beforeUpdate') } } }, true /* isRenderWatcher */)
在 get() 中先調(diào)用了 pushTarget(this) 將 Dep.target 指向當(dāng)前的渲染 watcher。然后調(diào)用了 this.getter.call(vm, vm),實際上意味著執(zhí)行了 vm._update(vm._render(), hydrating)。vm._render() 返回了一個 vnode,vm._update完成頁面更新。在這個過程中會對 vm 上的數(shù)據(jù)訪問,這個時候就觸發(fā)了數(shù)據(jù)對象的 getter。
// this.getter = expOrFn = updateComponent() value = this.getter.call(vm, vm)
數(shù)據(jù)的 getter 中觸發(fā) dep.depend() 進(jìn)行依賴收集。
get: function reactiveGetter () { const value = getter ? getter.call(obj) : val if (Dep.target) { dep.depend() if (childOb) { childOb.dep.depend() if (Array.isArray(value)) { dependArray(value) } } } return value },
當(dāng)依賴收集完成后會popTarget(),恢復(fù) Dep.target() = null。最后清空這些依賴。
popTarget() this.cleanupDeps()
數(shù)據(jù)變化時,如何進(jìn)行更新?
數(shù)據(jù)更新時,會執(zhí)行setter,首先會對這個新值 newVal observe(newVal),再調(diào)用這個屬性的 dep.notify() 通知它的訂閱者們進(jìn)行更新。
總結(jié)
- Vue 初始化時就會通過 Object.defineProperty 攔截屬性的 getter 和 setter ,為對象的每個值創(chuàng)建一個 dep 并用 Dep.addSub() 來存儲該屬性值的 watcher 列表。
- 觸發(fā)依賴收集的階段是在 beforeMount 時,它會為組件創(chuàng)建一個渲染 Watcher,在執(zhí)行 render 的過程中就會觸發(fā)對象的 getter 方法,通過dep.depend()將訂閱者收集起來。通俗的來說,渲染的時候會先解析模板,由于模板中有使用到 data 中的數(shù)據(jù),所以會觸發(fā) get 操作,從將渲染的 Watcher 對象搜集起來,以便在 set 的時候批量更新。
參考資料
到此這篇關(guān)于Vue 響應(yīng)式系統(tǒng)依賴收集過程分析的文章就介紹到這了,更多相關(guān)Vue 響應(yīng)式系統(tǒng)依賴收集內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于vue-cli3+typescript的tsx開發(fā)模板搭建過程分享
這篇文章主要介紹了搭建基于vue-cli3+typescript的tsx開發(fā)模板,本文通過實例代碼截圖的形式給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02vue中el-table實現(xiàn)可拖拽移動列和動態(tài)排序字段
最近公司需要做個項目,需要拖拽表格和自定義表格字段,本文主要介紹了vue中el-table實現(xiàn)可拖拽移動列和動態(tài)排序字段,具有一定吃參考價值,感興趣的可以了解一下2023-12-12Vue-cli項目獲取本地json文件數(shù)據(jù)的實例
下面小編就為大家分享一篇Vue-cli項目獲取本地json文件數(shù)據(jù)的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03Vue中的數(shù)據(jù)監(jiān)聽和數(shù)據(jù)交互案例解析
這篇文章主要介紹了Vue中的數(shù)據(jù)監(jiān)聽和數(shù)據(jù)交互案例解析,在文章開頭部分先給大家介紹了vue中的數(shù)據(jù)監(jiān)聽事件$watch,具體代碼講解,大家可以參考下本文2017-07-07