Vue.js的响应式系统原理

Vue.js的响应式系统原理

写在前面

Vue.js是一款MVVM框架,核心思想是数据驱动视图,数据模型仅仅是普通的 JavaScript 对象。而当修改它们时,视图会进行更新。实现这些的核心就是“响应式系统”。

我们在开发过程中可能会存在这样的疑问:

  1. Vue.js把哪些对象变成了响应式对象?
  2. Vue.js究竟是如何响应式修改数据的?
  3. 上面这幅图的下半部分是怎样一个运行流程?
  4. 为什么数据有时是延时的(即什么情况下要用到nextTick)?

实现一个简易版的响应式系统

响应式系统核心的代码定义在src/core/observer中:

这部分的代码是非常多的,为了让大家对响应式系统先有一个印象,我在这里先实现一个简易版的响应式系统,麻雀虽小五脏俱全,可以结合开头那张图的下半部分来分析,写上注释方便大家理解。

 /**
 * 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中:

当用new关键字来实例化Vue时,会执行_init方法,定义在src/core/instance/init.js中,关键代码如下图:

在这当中调用来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
    }
  }
}

最后

响应式系统的原理基本梳理完了,现在再回过头来看这幅图的下半部分是不是清晰来呢。

评论 抢沙发

表情
  1. #1

    来自辽宁沈阳的用户 3天前
    老衲喜欢这篇文章

  2. #2

    来自北京昌平的用户 3天前
    点赞,前排摸大佬沾点技术

  3. #3

    来自河北石家庄的用户 4天前
    可以说是相当详细了

  4. #4

    来自北京朝阳的用户 4天前
    满满的干货,受益匪浅!如果排版再弄好看点,可能点赞数更高

  5. #5

    来自重庆万州的用户 10天前
    优秀,先收藏了。

  6. #6

    来自四川成都的用户 14天前
    good

  7. #7

    来自北京朝阳的用户 15天前
    有发布到github吗?