Vue的特色之一是響應式,視圖隨着數據的更新而更新,在視圖中修改數據後Vue實例中的數據也會同步更新。內部藉助依賴(下文中的Dep類)來實現,數據的獲取(即get操做)會觸發收集依賴,而對數據賦值(即set操做)會通知依賴數據更新,從新渲染視圖。對數據的get/set操做的攔截藉助的是ES5的Object.defineProperty
。html
在Vue源碼內,Dep類做爲依賴,Watcher類則用來收集依賴和通知依賴從新求值。對於在實例化時傳入的數據,使用工廠函數defineReactive
令其響應式。而在實例後再經過Vue.set/vm.$set
添加的響應式數據,則須要藉助Observer類來使其成爲響應式數據,最後也是經過defineReactive
實現響應式。vue
對於每一個響應式數據,會有兩個Dep實例,第一個是在defineReactive
中的閉包遍歷,用途顯而易見。而第二個Dep則在響應式數組的__ob__
屬性值中,這個值是Observer實例,其實例屬性dep是Dep實例,在執行Vue.set/vm.$set
添加響應式數據後,會通知依賴更新。react
在講defineReactive
以前,先講一下這些輔助類的實現和用處。git
咱們都知道,Vue響應式的實現,會在getter中收集響應式數據的依賴,在setter中通知依賴數據更新,從新計算數據而後來更新視圖。在Vue內部,使用Dep實例表示依賴,讓咱們看一下Dep類是怎麼定義的。github
Dep有兩個實例屬性,一個靜態屬性。靜態屬性target
是Watcher
實例,功能是從新求值和通知視圖更新,下文咱們會講到。實例屬性id
是Dep實例的惟一標識,無需多說;屬性subs
是Watcher實例數組,用於收集Watcher實例,當依賴更新時,這些Watcher實例就會從新求值。express
export default class Dep { static target: ?Watcher; id: number; subs: Array<Watcher>; constructor () { this.id = uid++ this.subs = [] } addSub (sub: Watcher) { this.subs.push(sub) } removeSub (sub: Watcher) { remove(this.subs, sub) } depend () { if (Dep.target) { Dep.target.addDep(this) } } notify () { // stabilize the subscriber list first const subs = this.subs.slice() for (let i = 0, l = subs.length; i < l; i++) { subs[i].update() } } }
方法addSub
用於添加Watcher
實例到subs
中,方法removeSub
用於從subs
移除Watcher
實例。數組
方法depond
會在收集依賴的時候調用,實際上執行了Watcher的實例方法addDep
,在addDep
內除了調用dep實例的addSup
方法外,還作了避免重複收集Watcher實例的工做。這個方法會在Vue爲響應式數據設置的自定義getter中執行。閉包
notify
方法則遍歷subs
,執行Watcher實例方法update來從新求值。這個方法會在Vue爲響應式數據設置的自定義setter中執行。架構
有人可能有疑問,target
是靜態屬性,那不是每一個實例的target都同樣的?實際上,從新求值的操做在Watcher實例方法get
內實現。在get方法內,會先調用pushTarget
來更新Dep.target
,使其指向當前Watcher實例,以前的`Dep.target
會被保存targetStack
末尾(至關於入棧操做),完成操做後會執行popTarget
函數,從targetStack
取出最後一個元素來還原Dep.target
(至關於出棧操做)。異步
Dep.target = null const targetStack = [] export function pushTarget (_target: ?Watcher) { if (Dep.target) targetStack.push(Dep.target) Dep.target = _target } export function popTarget () { Dep.target = targetStack.pop() }
當依賴更新時,Watcher類會從新求值,並可能觸發重渲染。
constructor ( vm: Component, expOrFn: string | Function, cb: Function, options?: ?Object, isRenderWatcher?: boolean ) { this.vm = vm // 與渲染相關的watcher if (isRenderWatcher) { vm._watcher = this } vm._watchers.push(this) // options if (options) { this.deep = !!options.deep this.user = !!options.user this.computed = !!options.computed this.sync = !!options.sync this.before = options.before } else { this.deep = this.user = this.computed = this.sync = false } this.cb = cb this.id = ++uid // uid for batching this.active = true this.dirty = this.computed // for computed 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 = 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 ) } } if (this.computed) { this.value = undefined this.dep = new Dep() } else { this.value = this.get() } }
構造函數接受五個參數,vm
是掛載的Component實例;expOrFn
是觀察的屬性,當是字符串時表示屬性名,是函數時會被當成屬性的get方法;cb
是屬性更新後執行的回調函數;options
是配置項;isRenderWatcher
表示當前實例是否與渲染相關。
在構造函數內,先將實例屬性vm
指向傳入的Component實例vm,若是當前Watcher實例與渲染相關,會將其保存在vm._watcher
中。接着將當前實例添加到vm._watchers
中,同時根據傳入的配置項options
初始化實例屬性。實例屬性getter
是監聽屬性的getter函數,若是expOrFn
是函數,直接賦值,不然會調用parsePath
來獲取屬性的getter。
parsePath
內部會先使用正則來判斷屬性名,若是有除數字、字母、.
和$
之外的字符時視爲非法屬性名,直接返回,因此屬性只能是以.
分隔的屬性。若是屬性名合法,則parsePath
返回一個閉包函數,調用時會傳入vm
,即obj
是vm
的引用,這個閉包函數最終的目的是從vm實例裏獲取屬性。
const bailRE = /[^\w.$]/ export function parsePath (path: string): any { if (bailRE.test(path)) { return } const segments = path.split('.') return function (obj) { for (let i = 0; i < segments.length; i++) { if (!obj) return obj = obj[segments[i]] } return obj } }
初始化完成以後,若是不是計算屬性相關的Watcher實例,會調用實例方法get
求值。
執行getter方法求值,完成依賴收集的過程。
方法開始時,執行pushTarget(this)
,將Dep.target
指向當前Watcher實例。而後執行getter
收集依賴,最後將Dep.target
復原,並執行cleanDeps
遍歷deps
。在每次求值以後,都會調用cleanupDeps
方法重置依賴,具體如何重置,稍後再講。
實際上,Dep.target
指向的實例是即將要收集的目標。
getter
的執行,除了會獲取值外,還會觸發在defineReactive
中爲屬性設置的getter,完成依賴的收集。
get () { pushTarget(this) let value const vm = this.vm try { value = this.getter.call(vm, vm) } catch (e) { if (this.user) { handleError(e, vm, `getter for watcher "${this.expression}"`) } else { throw e } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value) } popTarget() this.cleanupDeps() } return value }
addDep
的功能是將當前Watcher實例添加到傳入的Dep實例屬性subs數組裏去。
addDep
接受一個Dep實例做爲參數,若是 dep.id
沒有在集合 newDepIds
之中,則添加。若是不在集合 depIds
中,則將當前實例添加到 dep.subs
中。 簡單來講,這裏的操做會避免重複收集依賴,這也是不直接調用dep.addSub(Dep.target)
的緣由。
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) } } }
從這裏能夠看出來Dep實例和Watcher實例會相互引用。Dep實例將Watcher實例保存在實例屬性subs
中,在響應式屬性調用setter
時,執行notify
方法,通知Watcher實例從新求值。
Watcher實例將Dep實例保存在集合newDeps
,目的是避免重複收集依賴,同時會執行Dep實例方法addDep
,將當前Watcher實例添加到Dep實例屬性subs
中。
對於Watcher來講,每次求值的依賴並不必定與上一次的相同,在每次執行get
以後,都會調用cleanupDeps
來重置收集的依賴。Watcher有四個實例屬性用於記錄依賴,分別是newDeps/newDepIds
與deps/depIds
。newDeps
與deps
是保存依賴的數組,newDepIds
與depIds
是保存依賴Id的集合。記錄上一次求值依賴的屬性是deps/depIds
,記錄下一次求值依賴的屬性是newDeps/newDepIds
(執行cleanupDeps
時已經調用過getter
從新求值了,因此說是上一次求值,下一次指的是下一次調用get
的時候)。
cleanupDeps () { let i = this.deps.length while (i--) { const dep = this.deps[i] if (!this.newDepIds.has(dep.id)) { dep.removeSub(this) } } // 交換depIds和newDepIds let tmp = this.depIds this.depIds = this.newDepIds this.newDepIds = tmp this.newDepIds.clear() // 交換deps和newDeps tmp = this.deps this.deps = this.newDeps this.newDeps = tmp this.newDeps.length = 0 }
首先遍歷deps
,若是這次求值的依賴在下一次求值中並不存在,則須要調用removeSub
方法,從subs
數組中移除當前Watcher實例。
接着交換newDeps/newDepIds
與deps/depIds
,並清空交換後的newDeps/newDepIds
。
Dep類的notify
方法用於通知觀察者從新求值,該方法內部實際是遍歷subs
數組,執行Watcher的update
方法。
update 方法定義以下。當實例與計算屬性相關時,xxx。若是不是計算屬性相關時,判斷是否須要同步觸發,同步觸發時調用run
,不然執行queueWatcher(this)
,交由調度模塊統一調度。
update () { if (this.computed) { if (this.dep.subs.length === 0) { this.dirty = true } else { this.getAndInvoke(() => { this.dep.notify() }) } } else if (this.sync) { this.run() } else { queueWatcher(this) } }
銷燬當前Watcher實例。$watch
方法返回一個函數,函數內部就是Watcher實例調用teardown
方法。
先判斷Watcher實例是否在活躍狀態。首先要從Vue實例的觀察者隊列_watchers
中移除當前實例,若是vm
正在銷燬,由於性能的問題會跳過這一操做。接着遍歷deps
,取消這些Dep實例對當前Watcher實例的訂閱。最後令this.active = false
,表示當前Watcher實例已被銷燬。
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) } let i = this.deps.length while (i--) { this.deps[i].removeSub(this) } this.active = false } }
不管是同步或異步更新,或者是計算屬性相關的Wathcer實例,最終求值都是經過getAndInvoke
方法。
getAndInvoke
接收一個回調函數,會在從新求值且值更新後執行。
當新值與當前值不一樣時會被斷定爲值已更新。當值是對象時且this.deep
爲真時也斷定爲值已更新,儘管引用不發生改變,但其屬性卻可能發生變化,爲避免屬性發生改變而Watcher判斷未更新的狀況出現。
getAndInvoke (cb: Function) { 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 this.dirty = false if (this.user) { try { cb.call(this.vm, value, oldValue) } catch (e) { handleError(e, this.vm, `callback for watcher "${this.expression}"`) } } else { cb.call(this.vm, value, oldValue) } } }
run方法內部只是對getAndInvoke
的封裝,傳入的回調函數是實例化時傳入的函數。執行以前會先判斷Watcher實例是否已棄用。
run () { if (this.active) { this.getAndInvoke(this.cb) } }
因爲篇幅的緣由,本文只簡單分析了輔助類和工廠函數的源碼和功能。乾巴巴地講了這麼多,如今來稍微捋一下。
Watcher類會保存響應式數據的getter函數,這個getter函數多是實例化參數expOrFn
(當其是函數類型時),也多是執行parsePath(expOrFn)
獲取到的getter函數。實例方法update對外暴露,用於從新求值,實際上執行真正求值操做的get方法。方法addDep接受一個Dep實例參數,在執行訂閱操做前還會執行兩個if判斷,避免重複訂閱。
Dep類表明依賴,實例屬性subs
是Watcher數組,表明訂閱了當前Dep實例的觀察者實例,depond方法收集依賴,notify方法通知觀察者實例從新求值。訂閱列表中可能會有與渲染相關的觀察者,因此可能會觸發重渲染。
Observer類與Vue.set/vm.$set
的聯繫比較大,因此分析放在後面。