這片文章主要是根據上一篇文章《淺析Vue源碼(三)—— initMixin(上)》去解讀 initMixin後續的執行過程,上篇咱們已經能夠看到,接下來主要會發生這幾個操做過程:vue
initLifecycle(vm)
initEvents(vm)
initRender(vm)
callHook(vm, 'beforeCreate')
initInjections(vm)
initState(vm)
initProvide(vm)
callHook(vm, 'created')
複製代碼
在瞭解以前,首選咱們須要瞭解一下響應式數據原理,也就是咱們常說的:訂閱-發佈 模式。react
接下來我主要從Observe、Observer、Watcher、Dep、defineReactive來解析:這個函數定義在core文件下observer的index.js文件中,傳送地址。git
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
嘗試建立一個Observer實例(__ob__),若是成功建立Observer實例則返回新的Observer實例,若是已有Observer實例則返回現有的Observer實例。
*/
export function observe (value: any, asRootData: ?boolean): Observer | void {
/*判斷是不是一個對象或者傳入的值是不是VNode的屬性*/
if (!isObject(value) || value instanceof VNode) {
return
}
let ob: Observer | void
/*這裏用__ob__這個屬性來判斷是否已經有Observer實例,若是沒有Observer實例則會新建一個Observer實例並賦值給__ob__這個屬性,若是已有Observer實例則直接返回該Observer實例*/
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__
} else if (
/*這裏的判斷是爲了確保value是單純的對象,而不是函數或者是Regexp等狀況。*/
shouldObserve &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (asRootData && ob) {
/*若是是,數據則計數,後面Observer中的observe的asRootData非true*/
ob.vmCount++
}
return ob
}
複製代碼
Vue的響應式數據都會有一個__ob__的屬性做爲標記,裏面存放了該屬性的觀察器,也就是Observer的實例,防止重複綁定。github
接下來看一下新建的Observer。Observer的做用就是遍歷對象的全部屬性將其進行雙向綁定。express
/**
* Observer class that is attached to each observed
* object. Once attached, the observer converts the target
* object's property keys into getter/setters that * collect dependencies and dispatch updates. */ 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 /* 將Observer實例綁定到data的__ob__屬性上面去,以前說過observe的時候會先檢測是否已經有__ob__對象存放Observer實例了,def方法定義能夠參考https://github.com/vuejs/vue/blob/dev/src/core/util/lang.js#L16 */ def(value, '__ob__', this) /* 若是是數組,將修改後能夠截獲響應的數組方法替換掉該數組的原型中的原生方法,達到監聽數組數據變化響應的效果。 這裏若是當前瀏覽器支持__proto__屬性,則直接覆蓋當前數組對象原型上的原生數組方法,若是不支持該屬性,則直接覆蓋數組對象的原型。 */ if (Array.isArray(value)) { const augment = hasProto ? protoAugment /*直接覆蓋原型的方法來修改目標對象*/ : copyAugment /*定義(覆蓋)目標對象或數組的某一個方法*/ augment(value, arrayMethods, arrayKeys) /*Github:https://github.com/answershuto*/ /*若是是數組則須要遍歷數組的每個成員進行observe*/ this.observeArray(value) } else { /*若是是對象則直接walk進行綁定*/ 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) /*walk方法會遍歷對象的每個屬性進行defineReactive綁定*/ for (let i = 0; i < keys.length; i++) { defineReactive(obj, keys[i]) } } /** * Observe a list of Array items. */ observeArray (items: Array<any>) { /*數組須要便利每個成員進行observe*/ for (let i = 0, l = items.length; i < l; i++) { observe(items[i]) } } } 複製代碼
Observer爲數據加上響應式屬性進行雙向綁定。若是是對象則進行深度遍歷,爲每個子對象都綁定上方法,若是是數組則爲每個成員都綁定上方法。api
若是是修改一個數組的成員,該成員是一個對象,那隻須要遞歸對數組的成員進行雙向綁定便可。但這時候出現了一個問題?若是咱們進行pop、push等操做的時候,push進去的對象根本沒有進行過雙向綁定,更別說pop了,那麼咱們如何監聽數組的這些變化呢? Vue.js提供的方法是重寫push、pop、shift、unshift、splice、sort、reverse這七個數組方法。修改數組原型方法的代碼能夠參考observer/array.js以及observer/index.js。不過接下來據說尤雨溪大神會經過proxy來監聽更多的數組變化哦~數組
observer/array.js
複製代碼
/*
* not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ import { def } from '../util/index' /*取得原生數組的原型*/ const arrayProto = Array.prototype /*建立一個新的數組對象,修改該對象上的數組的七個方法,防止污染原生數組方法*/ export const arrayMethods = Object.create(arrayProto) /*這裏重寫了數組的這些方法,在保證不污染原生數組原型的狀況下重寫數組的這些方法,截獲數組的成員發生的變化,執行原生數組操做的同時dep通知關聯的全部觀察者進行響應式處理*/ const methodsToPatch = [ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] /** * Intercept mutating methods and emit events */ methodsToPatch.forEach(function (method) { // cache original method /*將數組的原生方法緩存起來,後面要調用*/ const original = arrayProto[method] def(arrayMethods, method, function mutator (...args) { /*調用原生的數組方法*/ const result = original.apply(this, args) /*數組新插入的元素須要從新進行observe才能響應式*/ const ob = this.__ob__ let inserted switch (method) { case 'push': case 'unshift': inserted = args break case 'splice': inserted = args.slice(2) break } if (inserted) ob.observeArray(inserted) // notify change /*dep通知全部註冊的觀察者進行響應式處理*/ ob.dep.notify() return result }) }) 複製代碼
從數組的原型新建一個Object.create(arrayProto)對象,經過修改此原型能夠保證原生數組方法不被污染。若是當前瀏覽器支持__proto__這個屬性的話就能夠直接覆蓋該屬性則使數組對象具備了重寫後的數組方法。若是沒有該屬性的瀏覽器,則必須經過遍歷def全部須要重寫的數組方法,這種方法效率較低,因此優先使用第一種。瀏覽器
在保證不污染不覆蓋數組原生方法添加監聽,主要作了兩個操做,第一是通知全部註冊的觀察者進行響應式處理,第二是若是是添加成員的操做,須要對新成員進行observe。緩存
可是修改了數組的原生方法之後咱們仍是無法像原生數組同樣直接經過數組的下標或者設置length來修改數組,能夠經過Vue.set以及splice方法。bash
Watcher是一個觀察者對象。依賴收集之後Watcher對象會被保存在Deps中,數據變更的時候會由Deps通知Watcher實例,而後由Watcher實例回調cb進行視圖的更新。
/* @flow */
import {
warn,
remove,
isObject,
parsePath,
_Set as Set,
handleError
} from '../util/index'
import { traverse } from './traverse'
import { queueWatcher } from './scheduler'
import Dep, { pushTarget, popTarget } from './dep'
import type { SimpleSet } 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.
*/
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;
before: ?Function;
getter: Function;
value: any;
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
this.vm = vm
/*_watchers存放訂閱者實例*/
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
/*把表達式expOrFn解析成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
)
}
}
this.value = this.lazy
? undefined
: this.get()
}
/**
* Evaluate the getter, and re-collect dependencies.
*/
/*得到getter的值而且從新進行依賴收集*/
get () {
/*將自身watcher觀察者實例設置給Dep.target,用以依賴收集。*/
pushTarget(this)
let value
const vm = this.vm
/*
執行了getter操做,看似執行了渲染操做,實際上是執行了依賴收集。
在將Dep.target設置爲自生觀察者實例之後,執行getter操做。
譬如說如今的的data中可能有a、b、c三個數據,getter渲染須要依賴a跟c,
那麼在執行getter的時候就會觸發a跟c兩個數據的getter函數,
在getter函數中便可判斷Dep.target是否存在而後完成依賴收集,
將該觀察者對象放入閉包中的Dep的subs中去。
*/
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
/*若是存在deep,則觸發每一個深層對象的依賴,追蹤其變化*/
if (this.deep) {
/*遞歸每個對象或者數組,觸發它們的getter,使得對象或數組的每個成員都被依賴收集,造成一個「深(deep)」依賴關係*/
traverse(value)
}
/*將觀察者實例從target棧中取出並設置給Dep.target*/
popTarget()
this.cleanupDeps()
}
return value
}
/**
* Add a dependency to this directive.
*/
/*添加一個依賴關係到Deps集合中*/
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) {
/*同步則執行run直接渲染視圖*/
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.
/*
即使值相同,擁有Deep屬性的觀察者以及在對象/數組上的觀察者應該被觸發更新,由於它們的值可能發生改變。
*/
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.
*/
/*收集該watcher的全部deps依賴*/
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實例的觀察者列表中將自身移除,因爲該操做比較耗費資源,因此若是vm實例正在被銷燬則跳過該步驟。*/
if (!this.vm._isBeingDestroyed) {
remove(this.vm._watchers, this)
}
let i = this.deps.length
while (i--) {
this.deps[i].removeSub(this)
}
this.active = false
}
}
}
複製代碼
Dep其實就是一個發佈者,能夠訂閱多個觀察者,依賴收集以後Deps中會存在一個或多個Watcher對象,在數據變動的時候通知全部的Watcher。
/* @flow */
import type Watcher from './watcher'
import { remove } from '../util/index'
import config from '../config'
let uid = 0
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
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)
}
/*依賴收集,當存在Dep.target的時候添加觀察者對象*/
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
/*通知全部訂閱者*/
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
if (process.env.NODE_ENV !== 'production' && !config.async) {
// subs aren't sorted in scheduler if not running async // we need to sort them now to make sure they fire in correct // order subs.sort((a, b) => a.id - b.id) } 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設爲null,防止後面重複添加依賴。*/ 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() } 複製代碼
接下來是defineReactive。defineReactive的做用是經過Object.defineProperty爲數據定義上getter\setter方法,進行依賴收集後閉包中的Deps會存放Watcher對象。觸發setter改變數據的時候會通知Deps訂閱者通知全部的Watcher觀察者對象進行視圖的更新。
/**
* Define a reactive property on an Object.
*/
export function defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
/*在閉包中定義一個dep對象*
const dep = new Dep()
const property = Object.getOwnPropertyDescriptor(obj, key)
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
/*若是以前該對象已經預設了getter以及setter函數則將其取出來,新定義的getter/setter中會將其執行,保證不會覆蓋以前已經定義的getter/setter。*/
const getter = property && property.get
const setter = property && property.set
if ((!getter || setter) && arguments.length === 2) {
val = obj[key]
}
/*對象的子對象遞歸進行observe並返回子節點的Observer對象*/
let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
/*若是本來對象擁有getter方法則執行*/
const value = getter ? getter.call(obj) : val
if (Dep.target) {
/*進行依賴收集*/
dep.depend()
if (childOb) {
/*子對象進行依賴收集,其實就是將同一個watcher觀察者實例放進了兩個depend中,一個是正在自己閉包中的depend,另外一個是子元素的depend*/
childOb.dep.depend()
if (Array.isArray(value)) {
/*是數組則須要對每個成員都進行依賴收集,若是數組的成員仍是數組,則遞歸。*/
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
/*經過getter方法獲取當前值,與新值進行比較,一致則不須要執行下面的操做*/
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方法則執行setter*/
setter.call(obj, newVal)
} else {
val = newVal
}
/*新的值須要從新進行observe,保證數據響應式*/
childOb = !shallow && observe(newVal)
/*dep對象通知全部的觀察者*/
dep.notify()
}
})
}
複製代碼
如今再來看這張圖官方提供的解析圖是否是更清晰了呢?
要是喜歡能夠給我一個star,github
在這裏要感謝染陌老師提供的思路。