由於對Vue.js很感興趣,並且平時工做的技術棧也是Vue.js,這幾個月花了些時間研究學習了一下Vue.js源碼,並作了總結與輸出。
文章的原地址:github.com/answershuto…。
在學習過程當中,爲Vue加上了中文的註釋github.com/answershuto…,但願能夠對其餘想學習Vue源碼的小夥伴有所幫助。
可能會有理解存在誤差的地方,歡迎提issue指出,共同窗習,共同進步。javascript
閱讀數據綁定源碼以前建議先了解一下《響應式原理》以及《依賴收集》,能夠更好地理解Vue.js數據雙向綁定的整個過程。html
前面已經講過Vue數據綁定的原理了,如今從源碼來看一下數據綁定在Vue中是如何實現的。vue
首先看一下Vue.js官網介紹響應式原理的這張圖。java
這張圖比較清晰地展現了整個流程,首先經過一次渲染操做觸發Data的getter(這裏保證只有視圖中須要被用到的data纔會觸發getter)進行依賴收集,這時候其實Watcher與data能夠當作一種被綁定的狀態(其實是data的閉包中有一個Deps訂閱着,在修改的時候會通知全部的Watcher觀察者),在data發生變化的時候會觸發它的setter,setter通知Watcher,Watcher進行回調通知組件從新渲染的函數,以後根據diff算法來決定是否發生視圖的更新。react
Vue在初始化組件數據時,在生命週期的beforeCreate與created鉤子函數之間實現了對data、props、computed、methods、events以及watch的處理。git
這裏來說一下initData,能夠參考源碼instance下的state.js文件,下面全部的中文註釋都是我加的,英文註釋是尤大加的,請不要忽略英文註釋,英文註釋都講到了比較關鍵或者晦澀難懂的點。github
加註釋版的vue源碼也能夠直接經過傳送門查看,這些是我在閱讀Vue源碼過程當中加的註釋,持續更新中。算法
initData主要是初始化data中的數據,將數據進行Oberver,監聽數據的變化,其餘的監視原理一致,這裏以data爲例。express
function initData (vm: Component) {
/*獲得data數據*/
let data = vm.$options.data
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
/*判斷是不是對象*/
if (!isPlainObject(data)) {
data = {}
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
)
}
// proxy data on instance
/*遍歷data對象*/
const keys = Object.keys(data)
const props = vm.$options.props
let i = keys.length
//遍歷data中的數據
while (i--) {
/*保證data中的key不與props中的key重複,props優先,若是有衝突會產生warning*/
if (props && hasOwn(props, keys[i])) {
process.env.NODE_ENV !== 'production' && warn(
`The data property "${keys[i]}" is already declared as a prop. ` +
`Use prop default value instead.`,
vm
)
} else if (!isReserved(keys[i])) {
/*判斷是不是保留字段*/
/*這裏是咱們前面講過的代理,將data上面的屬性代理到了vm實例上*/
proxy(vm, `_data`, keys[i])
}
}
// observe data
/*從這裏開始咱們要observe了,開始對數據進行綁定,這裏有尤大大的註釋asRootData,這步做爲根數據,下面會進行遞歸observe進行對深層對象的綁定。*/
observe(data, true /* asRootData */)
}複製代碼
其實這段代碼主要作了兩件事,一是將_data上面的數據代理到vm上,另外一件事經過observe將全部數據變成observable。數組
接下來看一下proxy代理。
/*添加代理*/
export function proxy (target: Object, sourceKey: string, key: string) {
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
}
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}複製代碼
這裏比較好理解,經過proxy函數將data上面的數據代理到vm上,這樣就能夠用app.text代替app._data.text了。
接下來是observe,這個函數定義在core文件下oberver的index.js文件中。
/** * 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 {
/*判斷是不是一個對象*/
if (!isObject(value)) {
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等狀況。*/
observerState.shouldConvert &&
!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的實例,防止重複綁定。
接下來看一下新建的Observer。Observer的做用就是遍歷對象的全部屬性將其進行雙向綁定。
/** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. */
export class {
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)
if (Array.isArray(value)) {
/* 若是是數組,將修改後能夠截獲響應的數組方法替換掉該數組的原型中的原生方法,達到監聽數組數據變化響應的效果。 這裏若是當前瀏覽器支持__proto__屬性,則直接覆蓋當前數組對象原型上的原生數組方法,若是不支持該屬性,則直接覆蓋數組對象的原型。 */
const augment = hasProto
? protoAugment /*直接覆蓋原型的方法來修改目標對象*/
: copyAugment /*定義(覆蓋)目標對象或數組的某一個方法*/
augment(value, arrayMethods, arrayKeys)
/*若是是數組則須要遍歷數組的每個成員進行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], 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爲數據加上響應式屬性進行雙向綁定。若是是對象則進行深度遍歷,爲每個子對象都綁定上方法,若是是數組則爲每個成員都綁定上方法。
若是是修改一個數組的成員,該成員是一個對象,那隻須要遞歸對數組的成員進行雙向綁定便可。但這時候出現了一個問題,?若是咱們進行pop、push等操做的時候,push進去的對象根本沒有進行過雙向綁定,更別說pop了,那麼咱們如何監聽數組的這些變化呢?
Vue.js提供的方法是重寫push、pop、shift、unshift、splice、sort、reverse這七個數組方法。修改數組原型方法的代碼能夠參考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)
/** * Intercept mutating methods and emit events */
/*這裏重寫了數組的這些方法,在保證不污染原生數組原型的狀況下重寫數組的這些方法,截獲數組的成員發生的變化,執行原生數組操做的同時dep通知關聯的全部觀察者進行響應式處理*/
;[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.forEach(function (method) {
// cache original method
/*將數組的原生方法緩存起來,後面要調用*/
const original = arrayProto[method]
def(arrayMethods, method, function mutator () {
// avoid leaking arguments:
// http://jsperf.com/closure-with-arguments
let i = arguments.length
const args = new Array(i)
while (i--) {
args[i] = arguments[i]
}
/*調用原生的數組方法*/
const result = original.apply(this, args)
/*數組新插入的元素須要從新進行observe才能響應式*/
const ob = this.__ob__
let inserted
switch (method) {
case 'push':
inserted = args
break
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.js提供了$set()及$remove()方法。
Watcher是一個觀察者對象。依賴收集之後Watcher對象會被保存在Deps中,數據變更的時候會因爲Deps通知Watcher實例,而後由Watcher實例回調cb進行實圖的更新。
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: ISet;
newDepIds: ISet;
getter: Function;
value: any;
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: Object
) {
this.vm = vm
/*_watchers存放訂閱者實例*/
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
/*把表達式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中去。 */
if (this.user) {
try {
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
/*若是存在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類。其實Dep就是一個發佈者,能夠訂閱多個觀察者,依賴收集以後Deps中會存在一個或多個Watcher對象,在數據變動的時候通知全部的Watcher。
/** * 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()
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,防止後面重複添加依賴。*/複製代碼
接下來是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 ) {
/*在閉包中定義一個dep對象*/
const dep = new Dep()
const property = Object.getOwnPropertyDescriptor(obj, key)
if (property && property.configurable === false) {
return
}
/*若是以前該對象已經預設了getter以及setter函數則將其取出來,新定義的getter/setter中會將其執行,保證不會覆蓋以前已經定義的getter/setter。*/
// cater for pre-defined getter/setters
const getter = property && property.get
const setter = property && property.set
/*對象的子對象遞歸進行observe並返回子節點的Observer對象*/
let childOb = 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 = observe(newVal)
/*dep對象通知全部的觀察者*/
dep.notify()
}
})
}複製代碼
如今再來看這張圖是否是更清晰了呢?
做者:染陌
Email:answershuto@gmail.com or answershuto@126.com
Github: github.com/answershuto
osChina:my.oschina.net/u/3161824/b…
轉載請註明出處,謝謝。
歡迎關注個人公衆號