Vue.js的響應式系統原理

慕晨同學發表於2018-08-26

寫在前面

Vue.js的響應式系統原理
Vue.js是一款MVVM框架,核心思想是資料驅動檢視,資料模型僅僅是普通的 JavaScript 物件。而當修改它們時,檢視會進行更新。實現這些的核心就是“響應式系統”。

我們在開發過程中可能會存在這樣的疑問:

  1. Vue.js把哪些物件變成了響應式物件?
  2. Vue.js究竟是如何響應式修改資料的?
  3. 上面這幅圖的下半部分是怎樣一個執行流程?
  4. 為什麼資料有時是延時的(即什麼情況下要用到nextTick)?

實現一個簡易版的響應式系統

響應式系統核心的程式碼定義在src/core/observer中:

Vue.js的響應式系統原理
這部分的程式碼是非常多的,為了讓大家對響應式系統先有一個印象,我在這裡先實現一個簡易版的響應式系統,麻雀雖小五臟俱全,可以結合開頭那張圖的下半部分來分析,寫上註釋方便大家理解。

 /**
 * Dep是資料和Watcher之間的橋樑,主要實現了以下兩個功能:
 * 1.用 addSub 方法可以在目前的 Dep 物件中增加一個 Watcher 的訂閱操作;
 * 2.用 notify 方法通知目前 Dep 物件的 subs 中的所有 Watcher 物件觸發更新操作。
 */
class Dep {
    constructor () {
        // 用來存放Watcher物件的陣列
        this.subs = [];
    }
    addSub (sub) {
        // 往subs中新增Watcher物件
        this.subs.push(sub);
    }
    // 通知所有Watcher物件更新檢視
    notify () {
        this.subs.forEach((sub) => {
            sub.update();
        })
    }
}

// 觀察者物件
class Watcher {
    constructor () {
        // Dep.target表示當前全域性正在計算的Watcher(當前的Watcher物件),在get中會用到
        Dep.target = this;
    }
    // 更新檢視
    update () {
        console.log("檢視更新啦");
    }
}

Dep.target = null;

class Vue {
    // Vue構造類
    constructor(options) {
        this._data = options.data;
        this.observer(this._data);
        // 例項化Watcher觀察者物件,這時候Dep.target會指向這個Watcher物件
        new Watcher();
        console.log('render', this._data.message);
    }
    // 對Object.defineProperty進行封裝,給物件動態新增setter和getter
    defineReactive (obj, key, val) {
        const dep = new Dep();
        Object.defineProperty(obj, key, {
            enumerable: true,
            configurable: true,
            get: function reactiveGetter () {
                // 往dep中新增Dep.target(當前正在進行的Watcher物件)
                dep.addSub(Dep.target);
                return val;         
            },
            set: function reactiveSetter (newVal) {
                if (newVal === val) return;
                // 在set的時候通知dep的notify方法來通知所有的Wacther物件更新檢視
                dep.notify();
            }
        });
    }
    // 對傳進來的物件進行遍歷執行defineReactive
    observer (value) {
        if (!value || (typeof value !== 'object')) {
            return;
        }
        Object.keys(value).forEach((key) => {
            this.defineReactive(value, key, value[key]);
        });
    }
}
let obj = new Vue({
  el: "#app",
  data: {
      message: 'test'
  }
})
obj._data.message = 'update'
複製程式碼

執行以上程式碼,列印出來的資訊為:

 render test
 檢視更新啦
複製程式碼

下面結合Vue.js原始碼來分析它的流程:

Object.defineProperty()

我們都知道響應式的核心是利用來ES5的Object.defineProperty()方法,這也是Vue.js不支援IE9一下的原因,而且現在也沒有什麼好的補丁來修復這個問題。具體的可以參考MDN文件。這是它的使用方法:

 /*
    obj: 目標物件
    prop: 需要操作的目標物件的屬性名
    descriptor: 描述符
    
    return value 傳入物件
*/
Object.defineProperty(obj, prop, descriptor)
複製程式碼

其中descriptor有兩個非常核心的屬性:get和set。在我們訪問一個屬性的時候會觸發getter方法,當我們對一個屬性做修改的時候會觸發setter方法。當一個物件擁有來getter方法和setter方法,我們可以稱這個物件為響應式物件。

從new Vue()開始

Vue實際上是一個用Function實現的類,定義在src/core/instance/index.js中:

Vue.js的響應式系統原理
當用new關鍵字來例項化Vue時,會執行_init方法,定義在src/core/instance/init.js中,關鍵程式碼如下圖:

Vue.js的響應式系統原理
在這當中呼叫來initState()方法,我們來看一下initState()方法幹了什麼,定義在src/core/instance/state.js中,關鍵程式碼如下圖:

Vue.js的響應式系統原理
可以看出來,initState方法主要是對props,methods,data,computed和watcher等屬性做了初始化操作。在這當中呼叫來initData方法,來看一下initData方法幹了什麼,定義在src/core/instance/state.js,關鍵程式碼如下圖:

Vue.js的響應式系統原理
其實這段程式碼主要做了兩件事,一是將_data上面的資料代理到vm上,另一件是通過observe將所有資料變成observable。值得注意的是data中key不能和props和methods中的key衝突,否則會產生warning。

Observer

接下來看Observer的定義,在/src/core/observer/index.js中:

/**
 * Observer class that is attached to each observed
 * object. Once attached, the observer converts the target
 * object's property keys into getter/setters that
 * collect dependencies and dispatch updates.
 */
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()
    this.vmCount = 0
    def(value, '__ob__', this)
    if (Array.isArray(value)) {
      const augment = hasProto
        ? protoAugment
        : copyAugment
      augment(value, arrayMethods, arrayKeys)
      this.observeArray(value)
    } else {
      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)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i])
    }
  }

  /**
   * Observe a list of Array items.
   */
  observeArray (items: Array<any>) {
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }
}
複製程式碼

注意看英文註釋,尤大把晦澀難懂的地方都已經用英文註釋寫出來。Observer它的作用就是給物件的屬性新增getter和setter,用來依賴收集和派發更新。walk方法就是把傳進來的物件的屬性遍歷進行defineReactive繫結,observeArray方法就是把傳進來的陣列遍歷進行observe。

defineReactive

接下來看一下defineReative方法,定義在src/core/observer/index.js中:

  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) {
      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.call(obj, newVal)
      } else {
        val = newVal
      }
      childOb = !shallow && observe(newVal)
      dep.notify()
    }
  })
複製程式碼

物件的子物件遞迴進行observe並返回子節點的Observer物件:

 childOb = !shallow && observe(val)
複製程式碼

如果存在當前的Watcher物件,對其進行依賴收集,並對其子物件進行依賴收集,如果是陣列,則對陣列進行依賴收集,如果陣列的子成員還是陣列,則對其遍歷:

if (Dep.target) {
    dep.depend()
        if (childOb) {
          childOb.dep.depend()
          if (Array.isArray(value)) {
            dependArray(value)
          }
    }
}
複製程式碼

執行set方法的時候,新的值需要observe,保證新的值是響應式的:

childOb = !shallow && observe(newVal)
複製程式碼

dep物件會執行notify方法通知所有的Watcher觀察者物件:

dep.notify()
複製程式碼

Dep

Vue.js的響應式系統原理
Dep是Watcher和資料之間的橋樑,Dep.target表示全域性正在計算的Watcher。來看一下依賴收集器Dep的定義,在/src/core/observer/dep.js中:

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的時候新增Watcher觀察者物件
  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,防止繼續收集依賴
複製程式碼

Watcher

Watcher是一個觀察者物件,依賴收集以後Watcher物件會被儲存在Deps中,資料變動的時候會由Deps通知Watcher例項。定義在/src/core/observer/watcher.js中:

/**
 * A watcher parses an expression, collects dependencies,
 * and fires callback when the expression value changes.
 * This is used for both the $watch() api and directives.
 */
export default class Watcher {
  vm: Component;
  expression: string;
  cb: Function;
  id: number;
  deep: boolean;
  user: boolean;
  computed: boolean;
  sync: boolean;
  dirty: boolean;
  active: boolean;
  dep: Dep;
  deps: Array<Dep>;
  newDeps: Array<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.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()
    }
  }

  /**
   * Evaluate the getter, and re-collect dependencies.
   */
  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
  }

  /**
   * Add a dependency to this directive.
   */
  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.computed) {
      // A computed property watcher has two modes: lazy and activated.
      // It initializes as lazy by default, and only becomes activated when
      // it is depended on by at least one subscriber, which is typically
      // another computed property or a component's render function.
      if (this.dep.subs.length === 0) {
        // In lazy mode, we don't want to perform computations until necessary,
        // so we simply mark the watcher as dirty. The actual computation is
        // performed just-in-time in this.evaluate() when the computed property
        // is accessed.
        this.dirty = true
      } else {
        // In activated mode, we want to proactively perform the computation
        // but only notify our subscribers when the value has indeed changed.
        this.getAndInvoke(() => {
          this.dep.notify()
        })
      }
    } else if (this.sync) {
      this.run()
    } else {
      queueWatcher(this)
    }
  }

  /**
   * Scheduler job interface.
   * Will be called by the scheduler.
   */
  run () {
    if (this.active) {
      this.getAndInvoke(this.cb)
    }
  }

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

  /**
   * Evaluate and return the value of the watcher.
   * This only gets called for computed property watchers.
   */
  evaluate () {
    if (this.dirty) {
      this.value = this.get()
      this.dirty = false
    }
    return this.value
  }

  /**
   * Depend on this watcher. Only for computed property watchers.
   */
  depend () {
    if (this.dep && Dep.target) {
      this.dep.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.
      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.js的響應式系統原理
響應式系統的原理基本梳理完了,現在再回過頭來看這幅圖的下半部分是不是清晰來呢。

相關文章