1. 程式人生 > 其它 >Vue響應式依賴收集原理分析-vue高階必備

Vue響應式依賴收集原理分析-vue高階必備

背景

在 Vue 的初始化階段,_init 方法執行的時候,會執行 initState(vm) ,它的定義在 src/core/instance/state.js 中。在初始化 data 和 props option 時我們注意 initProps 和 initData 方法中都呼叫了 observe 方法。通過 observe (value),就可以將資料變成響應式。

export function initState (vm: Component) {
  vm._watchers = []
  const opts = vm.$options
  if (opts.props) initProps(vm, opts.props)
  if (opts.methods) initMethods(vm, opts.methods)
  if (opts.data) {
    initData(vm)
  } else {
    observe(vm._data = {}, true /* asRootData */)
  }
  if (opts.computed) initComputed(vm, opts.computed)
  if (opts.watch && opts.watch !== nativeWatch) {
    initWatch(vm, opts.watch)
  }
}
  • initProps

    if (value === undefined) {
      observe(value);
    }
    
  • initData

    observe(data, true /* asRootData */)
    

目標

  • 理解 Vue 資料響應式原理,瞭解響應式原理依賴收集的過程
  • 瞭解在什麼階段會觸發依賴收集

原始碼解讀

入口函式:observe

observe 方法定義在 src/core/observer/index.js 中。如果是一個非 VNode 的物件型別的資料,它會嘗試給這個值去建立一個 observer 例項,如果建立成功,返回新的 observer。或者如果 ob 已經存在了,就會直接返回一個現有的 observer。

/** * 嘗試給這個值去建立一個 observer 例項,如果建立成功,返回新的 observer  * 或者如果值已經有了,返回一個現有的 observer * @param {*} value  * @param {boolean} asRootData  * @returns Observer | void */
export function observe (value: any, asRootData: ?boolean): Observer | void {
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  let ob: Observer | void
  // 如果 value 已經有 observer,就返回現有的 observer
  // 否則如果不是伺服器渲染,value是陣列或者物件,value 是可擴充套件的,value 不是 vue 例項,就建立一個新的 observer
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
    ob = value.__ob__
  } else if (
    shouldObserve &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    ob = new Observer(value)
  }
  // 如果是根元件,vmCount 不為0
  if (asRootData && ob) {
    ob.vmCount++
  }
  return ob
}

通過 new Observer(value) 可以給 value 建立一個 observer 例項,那麼 Observer 類的定義和作用是什麼?在同一個檔案下可以看到 class Observer 是如何定義的。

class Observer

Observer 方法定義在 src/core/observer/index.js 中。在它的建構函式中,首先例項化 Dep 物件(主要用來存放它的 watcher列表),接著通過執行 def 函式把自身例項新增到資料物件 value 的 ob 屬性上,所以存在 ob 屬性意味著已經被觀察過。最後判斷 value 為陣列的情況下,會陣列項遍歷,給陣列的每一項建立一個 observe 例項;如果是物件,那麼遍歷所有的屬性,通過Object.defineProperty修改getter/setters。

/** * Observer 類和每個響應式物件關聯。 * observer 會轉化物件的屬性值的 getter/setters 方法收集依賴和派發更新。 */
export class Observer {
  value: any;
  dep: Dep;
  vmCount: number; // number of vms that have this object as root $data

  constructor(value: any) {
    this.value = value
    this.dep = new Dep() // 存放 Observer 的 watcher 列表
    this.vmCount = 0
    def(value, '__ob__', this) // __ob__ 指向自身 observe 例項,存在 __ob__ 屬性意味著已經被觀察過
    // 如果是陣列
    if (Array.isArray(value)) {
      // hasProto = '__proto__' in {} 判斷物件是否存在 __proto__ 屬性
      if (hasProto) {
        // 如果有 __proto__,就將 value.__proto__ 指向 arrayMethods
        protoAugment(value, arrayMethods)
      } else {
        // 否則,就遍歷 arrayMethods,將值複製到 value 上
        copyAugment(value, arrayMethods, arrayKeys)
      }
      this.observeArray(value) // 陣列項遍歷,給陣列的每一項建立一個 observe 例項
    } else {
      this.walk(value) // 遍歷所有的屬性,修改 getter/setters
    }
  }

  // 遍歷所有的屬性,修改 getter/setters,這個方法只有在 value 是object時呼叫
  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i])
    }
  }

  // 陣列項遍歷,給陣列的每一項建立一個 observe 例項
  observeArray (items: Array<any>) {
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }
}

我們來看看對於陣列和物件, Observe 分別做了什麼處理。

Observe 如何處理陣列

首先,對於 value 為陣列而言,由於 proto 不是標準屬性,有些瀏覽器不支援,比如 IE6-10,Opera10.1,所以需要根據物件是否存在 proto 屬性區分在原型鏈上新增方法, protoAugment 和 copyAugment 都是在目標物件上新增屬性值。

/** * 將 target.__proto__ 指向 src * 攔截原型鏈__proto__,來增強目標物件或陣列 * @param {*} target  * @param {Object} src  */
function protoAugment (target, src: Object) {
  /* eslint-disable no-proto */
  target.__proto__ = src
  /* eslint-enable no-proto */
}

/** * 遍歷 key 屬性值列表,將 src 中的 key 屬性值逐一定義到 target 的屬性中 * 通過定義隱藏屬性,來增強目標物件或陣列 * @param {Object} target  * @param {Object} src  * @param {Array<string>} keys  */
/* istanbul ignore next */
function copyAugment (target: Object, src: Object, keys: Array<string>) {
  for (let i = 0, l = keys.length; i < l; i++) {
    const key = keys[i]
    def(target, key, src[key]) // // 為 target 定義 key 和值
  }
}

在原型鏈上新增的屬性方法 arrayMethods 在 src/core/observer/array.js 可以找到他的定義。實際上 arrayMethods 就是 push pop shift unshift splice sort reverse 七個個方法。這麼做的目的是因為要通過 proto 操作資料的原型鏈,覆蓋陣列預設的七個原型方法,以實現陣列響應式。

Observe 如何處理物件

其次,對於物件而言,會去遍歷物件的每個 key,呼叫 defineReactive(obj, keys[i]) 方法。它會為 obj[key] 建立一個依賴類 dep(會幫這個key 定義一個 id 和 subs(watcher 訂閱者列表) 方便依賴收集)然後再利用 Object.defineProperty 對物件的 get 和 set 方法做了處理。get 攔截對 obj[key] 的讀取操作,set 攔截對 obj[key] 的寫操作。

/** * 在物件上定義一個響應式的屬性。 * @param {Object} obj  * @param {string} key  * @param {*} val  * @param {*} customSetter  * @param {*} shallow  * @returns  */
export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  const dep = new Dep() // 為 Object 的 key 建立一個依賴類,會幫這個key 定義一個 id 和 subs(watcher 訂閱者列表)

  const property = Object.getOwnPropertyDescriptor(obj, key)
  // 獲取 obj[key] 的屬性描述符,發現它是不可配置物件的話直接 return
  if (property && property.configurable === false) {
    return
  }

  // cater for pre-defined getter/setters
  const getter = property && property.get
  const setter = property && property.set
  if ((!getter || setter) && arguments.length === 2) {
    val = obj[key]
  }
  // 對 obj[key] 進行觀察,保證物件中的所有 key 都被觀察
  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()
        if (childOb) {
          childOb.dep.depend()
          if (Array.isArray(value)) {
            dependArray(value)
          }
        }
      }
      return value
    },
    set: function reactiveSetter (newVal) {
      // 舊的 obj[key]
      const value = getter ? getter.call(obj) : val
      // 如果新老值一樣,則直接 return,不跟新更不觸發響應式更新過程
      /* 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()
      }
      // setter 不存在說明該屬性是一個只讀屬性,直接 return
      // #7981: for accessor properties without setter
      if (getter && !setter) return
      // 設定新值
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      // 對新值進行觀察,讓新值也是響應式的
      childOb = !shallow && observe(newVal)
      dep.notify() // 通知依賴的觀察者更新
    }
  })
}

參考 Vue面試題詳細解答

可以看到,defineReactive(obj, keys[i]) 中對物件做了處理,不論巢狀的多深,都會 observe(value) 繼續觀察,在設定了新的值後,也會重新對新值進行觀察,讓新值也是響應式的。

上面的程式碼中,在 Observer 類建構函式執行時建立了一個 new Dep(),之後在定義物件的響應式屬性時,也為 Object 的 key 建立一個依賴類 const dep = new Dep(),然後在 set 資料值會觸發 dep.notify()。那麼 Dep 的作用是什麼呢?

class Dep

Dep 類的定義在 src/core/observer/dep.js 下。它的建構函式中定義了 id 和一個用於儲存訂閱這個 dep 的 watcher 的陣列 subs[]。

/** * 一個 dep 對應一個 object.key,每次 key 更新時呼叫 dep.notify(), * dep 下的 subs 存放 Watcher 列表,可以呼叫 dep.notify() 觸發 watcher.update() 使 Watcher 列表更新。 */
export default class Dep {
  static target: ?Watcher; // Dep 類的靜態屬性,可以使用 Dep.target 訪問,內容是 Watcher
  id: number;
  subs: Array<Watcher>; // Watcher 組成的訂閱列表

  constructor() {
    this.id = uid++
    this.subs = [] // watcher 訂閱者列表
  }

  // 向訂閱者列表中新增一個訂閱者 Watcher
  addSub (sub: Watcher) {
    this.subs.push(sub)
  }

  // 從訂閱者列表中刪掉一個 Watcher
  removeSub (sub: Watcher) {
    remove(this.subs, sub)
  }

  // 讓全域性唯一的 watcher 添加當前的依賴
  depend () {
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }

  // 通知訂閱者列表觸發更新
  notify () {
    // 用 slice() 方法拷貝一個 subs,不影響 this.subs
    const subs = this.subs.slice()
    if (process.env.NODE_ENV !== 'production' && !config.async) {
      // 如果不是執行非同步,Watcher 列表不會在排程器中排序,我們需要去對他們進行排序以確保他們按順序正確的排程
      subs.sort((a, b) => a.id - b.id)
    }
    // 依次觸發 Watcher.update()
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}

Dep.target

這裡的 Dep.target 就是一個 watcher例項,在依賴收集時會呼叫 watcher.addDep(this) 向觀察者中新增自己這個依賴。 Dep.notify() 會通知這個依賴的觀察者們依次觸發 Watcher.update()。

Dep.target 是當前正在執行的 watcher,同一時間只會有一個 watcher 在執行。

Dep.target = null
const targetStack = []

// 在需要進行依賴收集的時候呼叫,設定 Dep.target = watcher
export function pushTarget (target: ?Watcher) {
  targetStack.push(target)
  Dep.target = target
}

// 依賴收集結束呼叫,設定 Dep.target 為對堆疊中前一個 watcher
export function popTarget () {
  targetStack.pop()
  Dep.target = targetStack[targetStack.length - 1]
}

class Watcher

Watcher類定義在 src/core/observer/watcher.js 中。一個元件渲染時建立一個 watcher。
或者一個表示式建立一個 Watcher ,當表示式發生改變時觸發排程。

Watcher 的原型方法中和依賴收集相關的方法有 get() addDep() cleanupDep()等。在 watcher 的建構函式中會呼叫它的原型方法 get(),它將 Dep.target 指向當前 watcher。

/** * Watcher 解析一個表示式,收集依賴,當表示式發生改變時觸發排程。Watcher 類用於 $watch() api 和指令。 */
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>; // deps 表示上一次新增的 Dep 例項陣列
  newDeps: Array<Dep>; // newDeps 表示新新增的 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
    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
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } else {
      this.getter = parsePath(expOrFn)
      if (!this.getter) {
        this.getter = noop
        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()
  }
  // 一些原型方法
  // 以下是定義在 watcher 類原型物件上的方法,用 Watcher.prototype.get() 訪問
  /**   * Evaluate the getter, and re-collect dependencies.   */
  get () {
    // 將 Dep.target 指向當前 watcher
    pushTarget(this)
    let value
    const vm = this.vm
    try {
      // 讓 vm 呼叫 this.getter,並傳入 vm 作為引數
      // this.getter = expOrFn
      value = this.getter.call(vm, vm)
    } catch (e) {
      if (this.user) {
        handleError(e, vm, `getter for watcher "${this.expression}"`)
      } else {
        throw e
      }
    } finally {
      // 如果需要監聽物件內部值的變化,那麼呼叫 traverse 方法
      if (this.deep) {
        traverse(value) // 遞迴遍歷 value 的每個屬性, 確保每個屬性都被監聽
      }
      // 當前 vm 的資料依賴收集已經完成,恢復 Dep.target
      popTarget()
      this.cleanupDeps()
    }
    return value
  }

  /**   * Add a dependency to this directive.   * 新增一個依賴:如果dep陣列中沒有dep.id,那麼觸發 dep 訂閱當前 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)
      }
    }
  }

  /**   * Clean up for dependency collection.   * 清除依賴收集   */
  cleanupDeps () {
    // 先保持 deps 和 newDepIds數量相同
    let i = this.deps.length
    while (i--) {
      const dep = this.deps[i]
      if (!this.newDepIds.has(dep.id)) {
        dep.removeSub(this) // 如果當前 dep 中沒有 newDepIds,就移除它的訂閱者列表
      }
    }
    // 更新 depIds、deps 為當前的 deps,然後清除 newDepIds 和 newDeps
    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) {
      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.
        isObject(value) ||
        this.deep
      ) {
        // set new value
        const oldValue = this.value
        this.value = value
        if (this.user) {
          const info = `callback for watcher "${this.expression}"`
          invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info)
        } 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.   * 從所有依賴項的訂閱者列表中刪除 self   */
  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
    }
  }
}

上面的流程是在 Vue 初始化時對資料做的處理,呼叫建立了 observe 例項和 dep 例項。但是並沒有提到 watcher 例項是在什麼時候建立的。我們先來看看一些使用 Watcher 的地方。

Watcher 的應用

  • beforeMount
    在 beforeMount 生命週期時,會通過 new Watcher 生成一個渲染 Watcher,它會在頁面渲染的過程中訪問每個資料物件的 getter 屬性,從而進行依賴的收集。
  • initComputed()
    遍歷 computed 中的每個 key,向 computed watcher 列表中新增一個 watcher 例項。
  • initWatch()
    遍歷 watch 中的每一個 key,呼叫 vm.$watch 建立一個 watcher 例項。

何時觸發依賴收集?

在 src/core/instance/lifecycle.js 中可以看到,在 beforeMount 階段例項化了一個 render watcher,並傳入一個 updateComponent 的 expOrFn 方法。之後 watcher 呼叫它的 this.get()。\

callHook(vm, 'beforeMount')

updateComponent = () => {
  vm._update(vm._render(), hydrating)
}

new Watcher(vm, updateComponent, noop, {
  before () {
    if (vm._isMounted && !vm._isDestroyed) {
      callHook(vm, 'beforeUpdate')
    }
  }
}, true /* isRenderWatcher */)

在 get() 中先呼叫了 pushTarget(this) 將 Dep.target 指向當前的渲染 watcher。然後呼叫了 this.getter.call(vm, vm),實際上意味著執行了 vm._update(vm._render(), hydrating)。vm._render() 返回了一個 vnode,vm._update完成頁面更新。在這個過程中會對 vm 上的資料訪問,這個時候就觸發了資料物件的 getter。

// this.getter = expOrFn = updateComponent()
value = this.getter.call(vm, vm)

資料的 getter 中觸發 dep.depend() 進行依賴收集。

get: function reactiveGetter () {
  const value = getter ? getter.call(obj) : val
  if (Dep.target) {
    dep.depend()
    if (childOb) {
      childOb.dep.depend()
      if (Array.isArray(value)) {
        dependArray(value)
      }
    }
  }
  return value
},

當依賴收集完成後會popTarget(),恢復 Dep.target() = null。最後清空這些依賴。

popTarget()
this.cleanupDeps()

資料變化時,如何進行更新?

資料更新時,會執行setter,首先會對這個新值 newVal observe(newVal),再呼叫這個屬性的 dep.notify() 通知它的訂閱者們進行更新。

總結

  • Vue 初始化時就會通過 Object.defineProperty 攔截屬性的 getter 和 setter ,為物件的每個值建立一個 dep 並用 Dep.addSub() 來儲存該屬性值的 watcher 列表。
  • 觸發依賴收集的階段是在 beforeMount 時,它會為元件建立一個渲染 Watcher,在執行 render 的過程中就會觸發物件的 getter 方法,通過dep.depend()將訂閱者收集起來。通俗的來說,渲染的時候會先解析模板,由於模板中有使用到 data 中的資料,所以會觸發 get 操作,從將渲染的 Watcher 物件蒐集起來,以便在 set 的時候批量更新。