Vue的響應式原理
Vue數據響應式原理的解讀有很多文章,此文只分享我對於Observer,Dep,Watcher的實現理解,希望此文對剛接觸Vue的開發者有所幫助。
Observer、Dep、Watcher簡介
- Observer:數據的觀察者,讓數據對象的讀寫操作都處於自己的監管之下。當初始化實例的時候,會遞歸遍歷data,用Object.defineProperty來攔截數據。
- Dep:數據更新的發佈者,get數據的時候,收集訂閱者,觸發Watcher的依賴收集,set數據時發佈更新,通知Watcher。
- Watcher:數據更新的訂閱者,get數據的時候,收集發佈者,訂閱的數據改變時執行相應的回調函數。
Observer
在Vue實例化的過程中會執行initState()和initData(),initData()中會執行observe(data, true /* asRootData */)。點擊此處查看initData代碼。此處爲observer代碼.
/**
* 執行var vm = new Vue() 時,會執行observe(data)
* 沒有被監聽的data需要New Observer()觀察;
*/
export function observe (value: any, asRootData: ?boolean): Observer | void {
if (!isObject(value) || value instanceof VNode) {
return
}
let ob: Observer | void
// 如果存在__ob__屬性,說明對象不是observer類,需要new Observer()
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__
} else if (
observerState.shouldConvert &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (asRootData && ob) {
// vmCount是用來記錄此Vue實例被使用的次數
ob.vmCount++
}
return ob
}
// observe執行後,不是observer類的執行new Observer
export class Observer {
value: any;
dep: Dep;
vmCount: number; // number of vms that has this object as root $data 記錄被使用的次數
constructor (value: any) {
this.value = value
this.dep = new Dep()
this.vmCount = 0
def(value, '__ob__', this)
// data是數組執行observeArray,是對象執行walk
if (Array.isArray(value)) {
const augment = hasProto
? protoAugment
: copyAugment
augment(value, arrayMethods, arrayKeys)
this.observeArray(value)
} else {
this.walk(value)
}
}
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
walk (obj: Object) {
// 獲取對象的屬性數組
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
// 執行 defineReactive(); params 依次是 data,key,value
defineReactive(obj, keys[i], obj[keys[i]])
}
}
/**
* Observe a list of Array items.
* 對於數組繼續執行observe(),對數組深入Observe.此時數組有對應的dep
*/
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
/**
* 執行observer後,value是對象在執行defineReactive(data,key,value)
* Define a reactive property on an Object.
*/
export function defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
const dep = new Dep()
// 指定對象上一個自有屬性對應的屬性描述符 (value,get,set,writable[屬性值是否可改],configurable[屬性描述是否可改],enumerable[對象屬性是否可枚舉])
const property = Object.getOwnPropertyDescriptor(obj, key)
// 對象的屬性描述不可更改時,返回
if (property && property.configurable === false) {
return
}
// 獲取getter和setter
// cater for pre-defined getter/setters
const getter = property && property.get
const setter = property && property.set
// 屬性值是對象或數組會進一步 defineReactive,不停深入建立observe
let childOb = !shallow && observe(val)
// 修改對象屬性的屬性描述符
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
// get 主要是訂閱者和發佈者互相收集的過程
get: function reactiveGetter () {
// get 觸發執行
const value = getter ? getter.call(obj) : val
// 此時Dep.target指向觸發get的watch,下文中描述
if (Dep.target) {
// 觸發get的watch收集dep發佈者
dep.depend()
// 屬性值是數組或對象時,會執行observe,執行observe會有dep屬性,其實就是使觸發get的watch收集child的dep
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
// set就比較好理解了
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
/* 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()
}
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
// 屬性值修改後,可能修改爲對象或數組,如果是就要建立observe觀察者,如果相反的話,就取消observe觀察者
childOb = !shallow && observe(newVal)
// 發佈者通知收集的訂閱者更新數據
dep.notify()
}
})
}
上述代碼執行 var vm = new Vue() --> observe(data) --> observer() --> defineReactive() 過程中可以分析出data不停的深入遍歷,直到不能建立觀察者爲之,給data和每個深入遍歷的屬性和對應屬性值爲對象或數組的建立觀察者。從set可以看出屬性值改變會觸發dep.notify()通知訂閱者更新數據。數據改變除了屬性值改變還有對象增刪屬性和數組修改,這就是爲什麼要給每個對象和數組建立觀察者了.請看下述代碼:
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
export function set (target: Array<any> | Object, key: any, val: any): any {
//對於數組的處理,調用變異方法splice,這個時候數組的Dep會發布更新消息
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key)
// 下述鏈接的代碼是給數組的常用操作添加數組Dep發佈通知
// https://github.com/vuejs/vue/blob/v2.5.13/src/core/observer/array.js
target.splice(key, 1, val)
return val
}
// 改變的是已經存在的屬性的屬性值
if (key in target && !(key in Object.prototype)) {
// 觸發該屬性對應的dep發佈訂閱者更新數據
target[key] = val
return val
}
const ob = (target: any).__ob__
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
)
return val
}
if (!ob) {
target[key] = val
return val
}
// 給新增屬性創建觀察者,用於收集訂閱者
defineReactive(ob.value, key, val)
// 對象的發佈者通知訂閱者更新數據,新增屬性的發佈者收集訂閱者
ob.dep.notify()
return val
}
/**
* Delete a property and trigger change if necessary.
*/
export function del (target: Array<any> | Object, key: any) {
//對於數組的處理,調用變異方法splice,這個時候數組的Dep會發布更新消息
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.splice(key, 1)
return
}
const ob = (target: any).__ob__
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid deleting properties on a Vue instance or its root $data ' +
'- just set it to null.'
)
return
}
if (!hasOwn(target, key)) {
return
}
// 刪除對象的屬性
delete target[key]
if (!ob) {
return
}
// 對象的發佈者通知訂閱者更新數據
ob.dep.notify()
}
/**
* Collect dependencies on array elements when the array is touched, since
* we cannot intercept array element access like property getters.
*/
function dependArray (value: Array<any>) {
for (let e, i = 0, l = value.length; i < l; i++) {
e = value[i]
e && e.__ob__ && e.__ob__.dep.depend()
if (Array.isArray(e)) {
dependArray(e)
}
}
}
1. 對象新增或刪除屬性時,是監控不到的。因爲開始oberve data的時候已經建立了getter,setter和發佈者,後面屬性新增和刪除是無法檢測到的。所以Vue給出了Vue.set和Vue.delete API。 當增刪屬性時或數組增刪元素時,就會觸發ob.dep.notify()通知訂閱者更新數據
2. 對於數組也可以通過Vue.set和Vue.delete API來修改,也可以調用數組的變異方法(push(),pop(),shift(),unshift(),splice(),sort(),reverse()),這些方法是會讓數組的值發生改變的,具體代碼請點擊查看
所以dep實例化的地方有兩處:
- 一處是在defineReactive函數裏,每次調用這個函數的時候都會創建一個新的Dep實例,存在在getter/setter閉包函數的作用域鏈上,是爲對象屬性服務的。在Watcher獲取屬性的值的時候收集訂閱者,在設置屬性值的時候發佈更新。
- 另一處是在observe函數中,此時的dep掛在被observe的數據的__ obj__屬性上,他是爲對象或數組服務的,在Watcher獲取屬性的值的時候,如果值被observe後返回observer對象(對象和數組纔會返回observer),那麼就會在此時收集訂閱者,在對象或數組增刪元素時調用$set等api時發佈更新的;
Dep
以下爲Dep的代碼,github地址爲點擊查看。
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
export default class Dep {
static target: ?Watcher;
id: number;
// subs用於收集訂閱者(watcher)
subs: Array<Watcher>;
constructor () {
this.id = uid++
this.subs = []
}
// 添加訂閱者
addSub (sub: Watcher) {
this.subs.push(sub)
}
// 移除訂閱者
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
// 訂閱者收集發佈者,並添加訂閱者(添加訂閱者是在watcher中調用dep的addSub方法,在watcher中會提到)
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
// 發佈通知,通知subs收集的訂閱者更新數據
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
// Dep.target指向當前的watcher
Dep.target = null
// 以下爲watcher中使用
// 存放watcher的
const targetStack = []
export function pushTarget (_target: Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = _target
}
export function popTarget () {
Dep.target = targetStack.pop()
}
在上文中我們提到Dep實例化的地方有兩處:
- 一處是在defineReactive函數裏,是爲對象屬性服務的,通過在get中childOb.dep.depend()收集訂閱者,通過在dep.notify()發佈更新。
- 另一處是在observe函數中,是爲對象或數組服務的,通過在get中childOb.dep.depend()收集訂閱者,通過在set,del和數組方法原型上ob.dep.notify() 發佈更新。
Watcher
以下爲Watcher的代碼,github地址爲點擊查看。
/**
* vm的$watch方法
* Vue.prototype.$watch()
* new Watcher(vm, expOrFn, cb, options)
* 傳參
* vm.$watch(userInfo, onUserInfoChange)
*/
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: SimpleSet;
newDepIds: SimpleSet;
getter: Function;
value: any;
// $watch 的params vm,userInfo,onUserInfoChange
constructor (
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
} 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
// getter有兩種情況,一種是function,例如掛載之後,獲取模板中的值,此時是一個函數,get中會觸發getter,一種是表達式,同時get也會觸發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
)
}
}
// 不是computed計算屬性時,都會調用get函數
this.value = this.lazy
? undefined
: this.get()
}
/**
* Evaluate the getter, and re-collect dependencies.
*/
get () {
// 入棧,此時Dep.target指向該watcher
pushTarget(this)
let value
const vm = this.vm
try {
// 觸發getter,這時對應的dep會觸發depend函數,depend函數觸發watcher的addDep函數,addDep收集完發佈者後,調用發佈者的addSub函數,使發佈者收集訂閱者,完成收集過程。
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()
// 更新deps和depIds,即去除不再依賴的發佈者
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.
* 發佈者發佈通知後更新數據,最終都會調用run方法
*/
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) {
// 觸發getter,訂閱者和發佈者相互重新收集
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.
*/
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.
*/
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
}
}
}
watcher初始化的時候會獲取getter函數,在執行get時,觸發了getter攔截,促使收集Dep和對應的Dep收集watch,完成了相互收集的過程。當發佈者通知watcher更新數據,執行update函數更新數據。
watcher中的deps和newDeps。他們是用來記錄已經記錄Watcher收集的依賴和新一輪Watcher收集的依賴,每一次有數據的更新都需要重新收集依賴,上述說到數據發佈更新後,會調用Dep的notify方法,notify方法會調用update,update調用run方法,run方法會調用get方法,重新獲取值,並重新收集依賴。收集完之後cleanupDeps函數,用於更新新的依賴。deps和newDeps作對比之前收集了但是新一輪沒收集,會執行對應dep的removeSub函數,使發佈者刪除watcher,因爲兩者不存在依賴關係了,這樣下次發佈者執行notify方法時不會再通知該watcher。
這裏可以看出Dep.target是全局唯一的,指向watcher,用於記錄當前的watcher。
數據響應式原理實現了數據到視圖的更新,而視圖到數據的更新,其實就是給表單元素(input等)添加了change等事件監聽,來動態修改model和 view。