淺析Vue響應式原理(一)

淺析Vue響應式原理(一)

Vue的特點之一是響應式,視圖隨着數據的更新而更新,在視圖中修改數據後Vue實例中的數據也會同步更新。內部藉助依賴(下文中的Dep類)來實現,數據的獲取(即get操作)會觸發收集依賴,而對數據賦值(即set操作)會通知依賴數據更新,重新渲染視圖。對數據的get/set操作的攔截藉助的是ES5的Object.defineProperty

總體架構簡介

在Vue源碼內,Dep類作爲依賴,Watcher類則用來收集依賴和通知依賴重新求值。對於在實例化時傳入的數據,使用工廠函數defineReactive令其響應式。而在實例後再通過Vue.set/vm.$set添加的響應式數據,則需要藉助Observer類來使其成爲響應式數據,最後也是通過defineReactive實現響應式。

對於每個響應式數據,會有兩個Dep實例,第一個是在defineReactive中的閉包遍歷,用途顯而易見。而第二個Dep則在響應式數組的__ob__屬性值中,這個值是Observer實例,其實例屬性dep是Dep實例,在執行Vue.set/vm.$set添加響應式數據後,會通知依賴更新。

在講defineReactive之前,先講一下這些輔助類的實現和用處。

Dep

我們都知道,Vue響應式的實現,會在getter中收集響應式數據的依賴,在setter中通知依賴數據更新,重新計算數據然後來更新視圖。在Vue內部,使用Dep實例表示依賴,讓我們看一下Dep類是怎麼定義的。

Dep有兩個實例屬性,一個靜態屬性。靜態屬性targetWatcher實例,功能是重新求值和通知視圖更新,下文我們會講到。實例屬性id是Dep實例的唯一標識,無需多說;屬性subs是Watcher實例數組,用於收集Watcher實例,當依賴更新時,這些Watcher實例就會重新求值。

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)
  }

  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()
    }
  }
}

方法addSub用於添加Watcher實例到subs中,方法removeSub用於從subs移除Watcher實例。

方法depond會在收集依賴的時候調用,實際上執行了Watcher的實例方法addDep,在addDep內除了調用dep實例的addSup方法外,還做了避免重複收集Watcher實例的工作。這個方法會在Vue爲響應式數據設置的自定義getter中執行。

notify方法則遍歷subs,執行Watcher實例方法update來重新求值。這個方法會在Vue爲響應式數據設置的自定義setter中執行。

有人可能有疑問,target是靜態屬性,那不是每個實例的target都一樣的?實際上,重新求值的操作在Watcher實例方法get內實現。在get方法內,會先調用pushTarget來更新Dep.target,使其指向當前Watcher實例,之前的`Dep.target會被保存targetStack末尾(相當於入棧操作),完成操作後會執行popTarget函數,從targetStack取出最後一個元素來還原Dep.target(相當於出棧操作)。

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()
}

Watcher

當依賴更新時,Watcher類會重新求值,並可能觸發重渲染。

constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {
    this.vm = vm
    // 與渲染相關的watcher
    if (isRenderWatcher) {
      vm._watcher = this
    }
    vm._watchers.push(this)
    // options
    if (options) {
      this.deep = !!options.deep
      this.user = !!options.user
      this.computed = !!options.computed
      this.sync = !!options.sync
      this.before = options.before
    } else {
      this.deep = this.user = this.computed = this.sync = false
    }
    this.cb = cb
    this.id = ++uid // uid for batching
    this.active = true
    this.dirty = this.computed // for computed 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 = 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
        )
      }
    }
    if (this.computed) {
      this.value = undefined
      this.dep = new Dep()
    } else {
      this.value = this.get()
    }
  }

構造函數接受五個參數,vm是掛載的Component實例;expOrFn是觀察的屬性,當是字符串時表示屬性名,是函數時會被當成屬性的get方法;cb是屬性更新後執行的回調函數;options是配置項;isRenderWatcher表示當前實例是否與渲染相關。

在構造函數內,先將實例屬性vm指向傳入的Component實例vm,如果當前Watcher實例與渲染相關,會將其保存在vm._watcher中。接着將當前實例添加到vm._watchers中,同時根據傳入的配置項options初始化實例屬性。實例屬性getter是監聽屬性的getter函數,如果expOrFn是函數,直接賦值,否則會調用parsePath來獲取屬性的getter。

parsePath內部會先使用正則來判斷屬性名,如果有除數字、字母、.$以外的字符時視爲非法屬性名,直接返回,所以屬性只能是以.分隔的屬性。如果屬性名合法,則parsePath返回一個閉包函數,調用時會傳入vm,即objvm的引用,這個閉包函數最終的目的是從vm實例裏獲取屬性。

const bailRE = /[^\w.$]/
export function parsePath (path: string): any {
  if (bailRE.test(path)) {
    return
  }
  const segments = path.split('.')
  return function (obj) {
    for (let i = 0; i < segments.length; i++) {
      if (!obj) return
      obj = obj[segments[i]]
    }
    return obj
  }
}

初始化完成之後,如果不是計算屬性相關的Watcher實例,會調用實例方法get求值。

get方法

執行getter方法求值,完成依賴收集的過程。

方法開始時,執行pushTarget(this),將Dep.target指向當前Watcher實例。然後執行getter收集依賴,最後將Dep.target復原,並執行cleanDeps遍歷deps。在每次求值之後,都會調用cleanupDeps方法重置依賴,具體如何重置,稍後再講。

實際上,Dep.target指向的實例是即將要收集的目標。

getter的執行,除了會獲取值外,還會觸發在defineReactive中爲屬性設置的getter,完成依賴的收集。

  get () {
    pushTarget(this)
    let value
    const vm = this.vm
    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
      if (this.deep) {
        traverse(value)
      }
      popTarget()
      this.cleanupDeps()
    }
    return value
  }

addDep

addDep的功能是將當前Watcher實例添加到傳入的Dep實例屬性subs數組裏去。

addDep接受一個Dep實例作爲參數,如果 dep.id 沒有在集合 newDepIds 之中,則添加。如果不在集合 depIds 中,則將當前實例添加到 dep.subs 中。 簡單來說,這裏的操作會避免重複收集依賴,這也是不直接調用dep.addSub(Dep.target)的原因。

  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)
      }
    }
  }

從這裏可以看出來Dep實例和Watcher實例會相互引用。Dep實例將Watcher實例保存在實例屬性subs中,在響應式屬性調用setter時,執行notify方法,通知Watcher實例重新求值。

Watcher實例將Dep實例保存在集合newDeps,目的是避免重複收集依賴,同時會執行Dep實例方法addDep,將當前Watcher實例添加到Dep實例屬性subs中。

cleanupDeps

對於Watcher來說,每次求值的依賴並不一定與上一次的相同,在每次執行get之後,都會調用cleanupDeps來重置收集的依賴。Watcher有四個實例屬性用於記錄依賴,分別是newDeps/newDepIdsdeps/depIdsnewDepsdeps是保存依賴的數組,newDepIdsdepIds是保存依賴Id的集合。記錄上一次求值依賴的屬性是deps/depIds,記錄下一次求值依賴的屬性是newDeps/newDepIds(執行cleanupDeps時已經調用過getter重新求值了,所以說是上一次求值,下一次指的是下一次調用get的時候)。

  cleanupDeps () {
    let i = this.deps.length
    while (i--) {
      const dep = this.deps[i]
      if (!this.newDepIds.has(dep.id)) {
        dep.removeSub(this)
      }
    }
    // 交換depIds和newDepIds
    let tmp = this.depIds
    this.depIds = this.newDepIds
    this.newDepIds = tmp
    this.newDepIds.clear()
    // 交換deps和newDeps
    tmp = this.deps
    this.deps = this.newDeps
    this.newDeps = tmp
    this.newDeps.length = 0
  }

首先遍歷deps,如果此次求值的依賴在下一次求值中並不存在,則需要調用removeSub方法,從subs數組中移除當前Watcher實例。

接着交換newDeps/newDepIdsdeps/depIds,並清空交換後的newDeps/newDepIds

update

Dep類的notify方法用於通知觀察者重新求值,該方法內部實際是遍歷subs數組,執行Watcher的update方法。

update 方法定義如下。當實例與計算屬性相關時,xxx。如果不是計算屬性相關時,判斷是否需要同步觸發,同步觸發時調用run,否則執行queueWatcher(this),交由調度模塊統一調度。

  update () {
    if (this.computed) {
      if (this.dep.subs.length === 0) {
        this.dirty = true
      } else {
        this.getAndInvoke(() => {
          this.dep.notify()
        })
      }
    } else if (this.sync) {
      this.run()
    } else {
      queueWatcher(this)
    }
  }

teardown

銷燬當前Watcher實例。$watch方法返回一個函數,函數內部就是Watcher實例調用teardown方法。

先判斷Watcher實例是否在活躍狀態。首先要從Vue實例的觀察者隊列_watchers中移除當前實例,如果vm正在銷燬,因爲性能的問題會跳過這一操作。接着遍歷deps,取消這些Dep實例對當前Watcher實例的訂閱。最後令this.active = false,表示當前Watcher實例已被銷燬。

  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
    }
  }

getAndInvoke

不論是同步或異步更新,或者是計算屬性相關的Wathcer實例,最終求值都是通過getAndInvoke方法。

getAndInvoke接收一個回調函數,會在重新求值且值更新後執行。

當新值與當前值不同時會被判定爲值已更新。當值是對象時且this.deep爲真時也判定爲值已更新,儘管引用不發生改變,但其屬性卻可能發生變化,爲避免屬性發生改變而Watcher判斷未更新的情況出現。

  getAndInvoke (cb: Function) {
    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
      this.dirty = false
      if (this.user) {
        try {
          cb.call(this.vm, value, oldValue)
        } catch (e) {
          handleError(e, this.vm, `callback for watcher "${this.expression}"`)
        }
      } else {
        cb.call(this.vm, value, oldValue)
      }
    }
  }

run

run方法內部只是對getAndInvoke的封裝,傳入的回調函數是實例化時傳入的函數。執行之前會先判斷Watcher實例是否已棄用。

  run () {
    if (this.active) {
      this.getAndInvoke(this.cb)
    }
  }

小結

由於篇幅的原因,本文只簡單分析了輔助類和工廠函數的源碼和功能。乾巴巴地講了這麼多,現在來稍微捋一下。

Watcher類會保存響應式數據的getter函數,這個getter函數可能是實例化參數expOrFn(當其是函數類型時),也可能是執行parsePath(expOrFn)獲取到的getter函數。實例方法update對外暴露,用於重新求值,實際上執行真正求值操作的get方法。方法addDep接受一個Dep實例參數,在執行訂閱操作前還會執行兩個if判斷,避免重複訂閱。

Dep類代表依賴,實例屬性subs是Watcher數組,代表訂閱了當前Dep實例的觀察者實例,depond方法收集依賴,notify方法通知觀察者實例重新求值。訂閱列表中可能會有與渲染相關的觀察者,所以可能會觸發重渲染。

Observer類與Vue.set/vm.$set的聯繫比較大,所以分析放在後面。

參考鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章