vue-源碼剖析-雙向綁定

項目中vue比較多,大概知道實現,最近翻了一下雙向綁定的代碼,這裏寫一下閱讀後的理解。vue

項目目錄

拉到vue的代碼以後,首先來看一下項目目錄,由於本文講的是雙向綁定,因此這裏主要看雙向綁定這塊的代碼。react

入口

從入口開始:src/core/index.js數組

index.js 比較簡單,第一句就引用了Vue進來,看下Vue是啥函數

import Vue from './instance/index'
複製代碼

Vue構造函數

來到 src/core/instance/index.jsui

一進來,嗯,沒錯,定義了Vue 構造函數,而後調用了好幾個方法,這裏咱們看第一個initMixinthis

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.jsspa

這個給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調用了initDatainitData調用了observe,而後咱們再往下找observecode

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 */)
}
複製代碼

Observer(觀察者)

來到 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()
    }
  })
}
複製代碼

Dep(訂閱者管理中心)

那麼,到這裏了,疑問的是何時會觸發Observerget方法來添加一個訂閱者呢?
這裏的條件是有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方法觸發Observerget方法將本身加入訂閱者

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)
    }
  }
}
複製代碼

Watcher(訂閱者)

又來到 src/core/observer/watcher.js
到這,addDep其實又調用時Dep實例的addSub方法,參數也是把Watcher實例傳遞過去
而後,咱們看上面的addSub,這裏就是把Watcher實例pushdepsubs數組中保存起來
到這裏,就完成了把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)
      }
    }
  }
}
複製代碼

走完了添加訂閱器,接着再來看下Observerset方法,這裏調用了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)
}
複製代碼

寫在最後

這裏的思路,其實就是翻着源碼走的,寫的時候都是按本身的理解思路來的,存在問題的話歡迎指出~

相關文章
相關標籤/搜索