項目中vue比較多,大概知道實現,最近翻了一下雙向綁定的代碼,這裏寫一下閱讀後的理解。vue
拉到vue的代碼以後,首先來看一下項目目錄,由於本文講的是雙向綁定,因此這裏主要看雙向綁定這塊的代碼。react
從入口開始:src/core/index.js
數組
index.js
比較簡單,第一句就引用了Vue
進來,看下Vue
是啥函數
import Vue from './instance/index'
複製代碼
來到 src/core/instance/index.js
ui
一進來,嗯,沒錯,定義了Vue
構造函數,而後調用了好幾個方法,這裏咱們看第一個initMixin
this
import { initMixin } from './init'
function Vue (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue)
) {
warn('Vue is a constructor and should be called with the `new` keyword')
}
this._init(options)
}
initMixin(Vue)
...
export default Vue
複製代碼
來到 src/core/instance/init.js
spa
這個給Vue
構造函數定義了_init
方法,每次new Vue
初始化實例時都會調用該方法。prototype
而後看到_init
中間的代碼,調用了好多初始化的函數,這裏咱們只關注data
的走向,因此這裏看一下initState
雙向綁定
export function initMixin (Vue: Class<Component>) {
Vue.prototype._init = function (options?: Object) {
const vm: Component = this
...
initState(vm)
...
}
}
複製代碼
來到 src/core/instance/state.js
initState
調用了initData
,initData
調用了observe
,而後咱們再往下找observe
code
import { observe } from '../observer/index'
export function initState (vm: Component) {
vm._watchers = []
const opts = vm.$options
...
if (opts.data) {
initData(vm)
} else {
observe(vm._data = {}, true /* asRootData */)
}
...
}
function initData (vm: Component) {
let data = vm.$options.data
...
observe(data, true /* asRootData */)
}
複製代碼
來到 src/core/observer/index.js
這裏,實例化Observer
對象
首先,new Observer
實例化一個對象,參數爲data
export function observe (value: any, asRootData: ?boolean): Observer | void {
let ob: Observer | void
ob = new Observer(value)
return ob
}
複製代碼
而後咱們來看下Observer
構造函數裏面寫了什麼,這裏給每一個對象加了value
和實例化了一個Dep
,而後data
爲數組的話則遞歸,不然執行walk
。
walk
這裏是對對象遍歷執行defineReactive
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()
if (Array.isArray(value)) {
...
this.observeArray(value)
} else {
this.walk(value)
}
}
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i])
}
}
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
複製代碼
而後,咱們來看defineReactive
作了什麼,嗯,這裏就是Observer
的核心。
用Object.defineProperty
對對象進行配置,重寫get&set
get
:對原來get
執行,而後執行dep.depend
添加一個訂閱者
set
:對原來set
執行,而後執行dep.notify
通知訂閱者
Dep
是幹啥的呢?Dep
實際上是一個訂閱者的管理中心,管理着全部的訂閱者
import Dep from './dep'
export function defineReactive ( obj: Object, key: string, val: any, customSetter?: ?Function, shallow?: boolean ) {
const dep = new Dep()
const property = Object.getOwnPropertyDescriptor(obj, key)
const getter = property && property.get
const setter = property && property.set
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()
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
dep.notify()
}
})
}
複製代碼
那麼,到這裏了,疑問的是何時會觸發Observer
的get
方法來添加一個訂閱者呢?
這裏的條件是有Dep.target
的時候,那麼咱們找一下代碼中哪裏會對Dep.target
賦值,找到了Dep
定義的地方
來到 src/core/observer/dep.js
pushTarget
就對Dep.target
賦值了,而後來看一下究竟是哪裏調用了pushTarget
export default class Dep {
...
}
Dep.target = null
const targetStack = []
export function pushTarget (_target: ?Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = _target
}
複製代碼
而後,找到了Watcher
調用了pushTarget
,那麼咱們來看一下Watcher
的實現
來到 src/core/observer/watcher.js
這裏能夠看到每次new Watcher
時,就會調用get
方法
這裏執行兩步操做
第一:調用pushTarget
第二:調用getter
方法觸發Observer
的get
方法將本身加入訂閱者
export default class Watcher {
vm: Component;
constructor (
vm: Component
) {
this.value = this.lazy
? undefined
: this.get()
}
get () {
pushTarget(this)
let value
const vm = this.vm
try {
value = this.getter.call(vm, vm)
}
return value
}
}
複製代碼
接着,Dep.target
有了以後,接下來就要看一下dep.depend()
這個方法,因此仍是要到Dep
來看下這裏的實現。 來到 src/core/observer/dep.js
這裏調用了Dep.target.addDep
的方法,參數是Dep
的實例對象,那麼咱們看下addDep
export default class Dep {
addSub (sub: Watcher) {
this.subs.push(sub)
}
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
}
複製代碼
又來到 src/core/observer/watcher.js
到這,addDep
其實又調用時Dep
實例的addSub
方法,參數也是把Watcher
實例傳遞過去
而後,咱們看上面的addSub
,這裏就是把Watcher
實例push
到dep
的subs
數組中保存起來
到這裏,就完成了把Watcher
加入到Dep
這裏訂閱器管理中心這裏,後面的管理就由Dep
來統一管理
export default class 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)
}
}
}
}
複製代碼
走完了添加訂閱器,接着再來看下Observer
的set
方法,這裏調用了dep.notify
,咱們來看一下這個方法
來到 src/core/observer/dep.js
這裏,就是對subs
中的全部Watcher
,調用其update
方法來更新數據
export default class Dep {
notify () {
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
複製代碼
這裏,咱們就來看看Watcher
是怎麼更新的 又來到 src/core/observer/watcher.js
update
調用的是run
方法,run
方法這裏先用get
拿到新的值,而後把新&舊值作爲參數給cb
調用
export default class Watcher {
update () {
this.run()
}
run () {
if (this.active) {
const value = this.get()
const oldValue = this.value
this.value = value
this.cb.call(this.vm, value, oldValue)
}
}
}
複製代碼
這裏的cb
實際上是實例化的時候傳進來的,這裏咱們看一下何時會實例化Watcher
回到一開始的initState:src/core/instance/state.js
initState
的最後還調用了initWatch
,而後再createWatcher
,最後$watch
的時候就實例化了Watcher
對象,這裏就把cb
傳到了Watcher
實例中,當監聽的數據改變的時候就會觸發cb
函數
import Watcher from '../observer/watcher'
export function initState (vm: Component) {
...
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
function initWatch (vm: Component, watch: Object) {
for (const key in watch) {
const handler = watch[key]
createWatcher(vm, key, handler)
}
}
function createWatcher ( vm: Component, expOrFn: string | Function, handler: any, options?: Object ) {
return vm.$watch(expOrFn, handler, options)
}
Vue.prototype.$watch = function ( expOrFn: string | Function, cb: any, options?: Object ): Function {
const vm: Component = this
const watcher = new Watcher(vm, expOrFn, cb, options)
}
複製代碼
這裏的思路,其實就是翻着源碼走的,寫的時候都是按本身的理解思路來的,存在問題的話歡迎指出~