Vue.js的響應式系統原理

文章首發於:github.com/USTB-musion…javascript

寫在前面

Vue.js是一款MVVM框架,核心思想是數據驅動視圖,數據模型僅僅是普通的 JavaScript 對象。而當修改它們時,視圖會進行更新。實現這些的核心就是「響應式系統」。java

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

  1. Vue.js把哪些對象變成了響應式對象?
  2. Vue.js到底是如何響應式修改數據的?
  3. 上面這幅圖的下半部分是怎樣一個運行流程?
  4. 爲何數據有時是延時的(即什麼狀況下要用到nextTick)?

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

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

這部分的代碼是很是多的,爲了讓你們對響應式系統先有一個印象,我在這裏先實現一個簡易版的響應式系統,麻雀雖小五臟俱全,能夠結合開頭那張圖的下半部分來分析,寫上註釋方便你們理解。github

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

執行以上代碼,打印出來的信息爲:express

render test
 視圖更新啦
複製代碼

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

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方法,咱們能夠稱這個對象爲響應式對象。markdown

從new Vue()開始

Vue其實是一個用Function實現的類,定義在src/core/instance/index.js中: 當用new關鍵字來實例化Vue時,會執行_init方法,定義在src/core/instance/init.js中,關鍵代碼以下圖:app

在這當中調用來initState()方法,咱們來看一下initState()方法幹了什麼,定義在src/core/instance/state.js中,關鍵代碼以下圖:

能夠看出來,initState方法主要是對props,methods,data,computed和watcher等屬性作了初始化操做。在這當中調用來initData方法,來看一下initData方法幹了什麼,定義在src/core/instance/state.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

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

最後

響應式系統的原理基本梳理完了,如今再回過頭來看這幅圖的下半部分是否是清晰來呢。

你能夠關注個人公衆號「慕晨同窗」,鵝廠碼農,日常記錄一些雞毛蒜皮的點滴,技術,生活,感悟,一塊兒成長。

相關文章
相關標籤/搜索