Vue数据响应式原理小结

216 阅读3分钟

Vue版本:2.6.14
最好是把Vue源码clone下来,边看边点

总所周知,Vue的响应式原理其实就是围绕 ObserverWatcherDep 这三个类实现的,经过对Vue源码的观看后,打算做一个小结,防止以后忘记,也算是梳理一下思路。

Observer

首先介绍的是Observer,它也是Vue对数据进行劫持的关键类。

在Vue初始化时会调用_init方法,下面的源码做了删减,从中可以看到一个initState(vm)的方法,这个方法就是Vue对我们在组件中定义的data、methods、props等等数据进行初始化,也是我们进行Observer介绍的入口

文件目录:src/core/instance/init.js

export function initMixin (Vue: Class<Component>) {
  Vue.prototype._init = function (options?: Object) {
    。。。
    initLifecycle(vm)
    initEvents(vm)
    initRender(vm)
    callHook(vm, 'beforeCreate')
    initInjections(vm)
    initState(vm)     // <--- 就是这个哦!!!
    initProvide(vm)
    callHook(vm, 'created')
    。。。
    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
  }
}

下面便从data上的数据维度来展开对Observer的分析:

initSate

文件目录:src/core/instance/state.js

initSate方法中可以看出,Vue是在这里对各种数据进行了初始化,那下面我们便只关注opts.data的判断即可

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

当组件中有data属性,便会执行initData(vm)方法

  if (opts.data) {
    initData(vm)
  } else {
    observe(vm._data = {}, true /* asRootData */)
  }

initData

文件目录:src/core/instance/state.js

function initData (vm: Component) {
  let data = vm.$options.data
  data = vm._data = typeof data === 'function'
    ? getData(data, vm)
    : data || {}
  。。。
  // proxy data on instance
  const keys = Object.keys(data)
  const props = vm.$options.props
  const methods = vm.$options.methods
  let i = keys.length
  while (i--) {
    const key = keys[i]
    。。。
    if (props && hasOwn(props, key)) {
      。。。
    } else if (!isReserved(key)) {
      proxy(vm, `_data`, key)
    }
  }
  // observe data
  observe(data, true /* asRootData */)
}

initData方法中可以看到,先是对data进行了类型判断,如果data是一个function,会去执行getData(data, vm)方法,否则直接将data赋值给_data,这个_data其实就是data的一个拷贝,后续对this实例进行劫持时也会用到这个_data,也就是proxy方法,那下面会讲。

getData方法其实做的事情也很简单,因为此时的data是一个函数,所以其中进行了正常的函数调用,然后还会执行pushTargetpopTarget,这两个方法后续会进行详细介绍,那在这里的目的其实就是置空Dep.target这个全局变量,现在可以不用理解。

接着大概说一下proxy函数,与响应式原理没什么关系但是我们日常开发中一直都会用到。我先抛一个问题:为什么我们在data上定义的变量,可以在methods中直接通过this.xx可以访问到?我们明明是定义在data上的呀,为什么可以直接在vue实例对象上拿到这个变量? 其实答案便是因为这个方法,仔细阅读以下代码就可以看出,其实Vue通过Object.defineProperty对this进行了劫持,当我们从this上直接访问属性的时候,其实return的是_data上的属性;当我们通过this.xx进行数据修改时,其实是对_data上的属性进行了修改。

target就是Vue实例;sourceKey就是_data;key就是对应的属性名

export function proxy (target: Object, sourceKey: string, key: string) {
  sharedPropertyDefinition.get = function proxyGetter () {
    return this[sourceKey][key]
  }
  sharedPropertyDefinition.set = function proxySetter (val) {
    this[sourceKey][key] = val
  }
  Object.defineProperty(target, key, sharedPropertyDefinition)
}

observe

文件目录:src/core/observer/index.js

oberve方法重点注意的就是ob = new Observer(value)这句话

那开头会有一个__ob__的处理,这个我们在控制台打印数据的时候也可以看到,每对一个对象进行实例化Observer类的时候就会给该对象添加一个__ob__标记,防止重复实例Observer,也可以理解成只有被Vue进行了数据响应处理的数据才会有这个标记。

export function observe (value: any, asRootData: ?boolean): Observer | void {
  。。。
  let ob: Observer | void
  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)
  }
  。。。
  return ob
}

Observer

Observer类中有一个constrcutor构造函数、两个原型方法:walk,observeArray。下面对这三部分介绍一下:

  constructor (value: any) {
    。。。
    this.dep = new Dep()   // <--- 第一个注意点
    。。。
    def(value, '__ob__', this)   // <--- 第二个注意点
    
    if (Array.isArray(value)) {   // <--- 第三个注意点
      if (hasProto) {
        protoAugment(value, arrayMethods)
      } else {
        copyAugment(value, arrayMethods, arrayKeys)
      }
      this.observeArray(value)
    } else {
      this.walk(value)
    }
  }

首先是this.dep = new Dep(),每次实例化Observer的时候都会给目前的对象实例化一个Dep,简单看一下Dep类

export default class Dep {
  static target: ?Watcher;
  id: number;
  subs: Array<Watcher>;

  constructor () {
    this.id = uid++
    this.subs = []
  }

  addSub (sub: Watcher) {
    。。。
  }

  removeSub (sub: Watcher) {
    。。。
  }

  depend () {
    。。。
  }

  notify () {
    。。。
  }
}

可以看到,实例化后的Dep其实生成了两个变量,一个是代表该dep实例对象的id,一个是subs数组。这两个变量在后面进行依赖收集的时候,id用于Watcher,subs用于存放对应的watcher实例,后续会进行详细介绍。

其次是def(value, '__ob__', this),给该对象添加__ob__标记,具体作用上面也有介绍。

接着便是对数据进行递归处理,那Vue在这个过程中会特意把类型是数组的摘出来单独处理

  1. 如果是数组的话,会对数组的原生方法进行劫持
  2. 如果是对象的话,正常往下走

这里简单说下为什么要对数组原生方法进行劫持(是我自己的理解不一定正确)。在Vue官方文档中提到过,Object.defineProperty无法对数组下标进行劫持所以这里特意处理了数组类型,那经过实践其实是可以劫持的,官方说法其实是有点不严谨的,我在一篇文章中看到尤雨溪被网友质问过,他做出的回答是可以对数组下标进行劫持,但是实现这个功能带来的收益和性能的消耗两者做了取舍。从这里也能看出在设计一门框架时,权衡也是一门艺术。当然了后续vue3用到了ES6的Proxy做代理,那这个我就没有研究过了。

回到正题,Vue对data上的数据进行递归处理,那最终都会走walk方法中的defineReactive方法

  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i])
    }
  }

defineReactive方法便是我们心心念念的setter、getter的核心方法,上代码:

export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  const dep = new Dep()

  。。。

  // cater for pre-defined getter/setters
  const getter = property && property.get
  const setter = property && property.set
  。。。

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

其实这个方法中需要注意的细节很多,但是说句实话,我们只是为了简单了解一下Vue2的响应式原理,所以个人认为没有必要搞那么细,Vue2已经成过去式了。

因此这里只简单介绍get和set:

一但数据被访问,便会触发get,这时dep.depend()dep实例对象便会调用原型方法depend,

  depend () {
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }

Dep.target这个全局变量其实就是存放的当前的Watcher实例,那这个变量是因为在实例化Watcher时,被watcher类的一个原型方法get()中执行了pushTarget(this)赋值的。

image.png

因此Dep.target.addDep(this)表示的就是调用当前watcher实例对象的一个原型方法addDep(dep: Dep),这里其实就是所谓的依赖收集进行的地方,最终会将watcher实例对象push到上面提到的subs数组中。

这个subs数组中存放的都是和目前对象数据相关的watcher实例,假如后面数据有变动便会触发set劫持,遍历这个subs数组,通知(其实就是调用watcher里面的一个updata方法)里面的每一个watcher实例,后面会详细介绍。

  // 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)
      }
    }
  }
  // Dep
  addSub (sub: Watcher) {
    this.subs.push(sub)
  }

下面先介绍一个Watcher类

Watcher

上代码:

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

  /**
   * 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.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 () {
    。。。
  }

  /**
   * Depend on all deps collected by this watcher.
   */
  depend () {
    let i = this.deps.length
    while (i--) {
      this.deps[i].depend()
    }
  }
  teardown () {
    。。。
  }
}

watcher的原型方法非常多,先看构造函数:

constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {
    。。。
    this.deps = []
    this.newDeps = []
    this.depIds = new Set()
    this.newDepIds = new Set()
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } else {
      this.getter = parsePath(expOrFn)
      。。。
    }
    this.value = this.lazy
      ? undefined
      : this.get()
  }

构造函数方法中,先定义了deps、newDeps、depIds、newDepIds四个变量,是在依赖收集的时候存放dep数据的,那这里为什么要分为old和new两种就不介绍了,自己看代码吧。

然后把expOrFn绑定到了getter上,这个expOrFn是一个方法,那具体其实涉及到了Vue数据驱动方面的东西了,这里不细说,目前只要知道执行getter方法其实就会进行生成虚拟DOM、转真实DOM的操作,而且在生成虚拟DOM的过程中是会对data上定义的数据进行访问,也就是会触发get劫持,进而启动Vue的依赖收集。

继续看Observer的构造函数,会执行原型方法get()

  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
  }

我们在前面说过get()方法会先把Dep.target这一全局变量指向当前的Watcher实例,然后执行getter方法,触发依赖收集。

那文章到这里,其实已经阐明了Observer的get劫持所做的事情以及初始时get这一劫持是在什么时候触发的(也就是依赖收集),那接下来就要介绍set劫持所做的事情,以及为什么要进行依赖收集

其实set劫持中有一行代码最醒目,那就是dep.notify()

   // Observer
    set: function reactiveSetter (newVal) {
      const value = getter ? getter.call(obj) : val
      。。。
      if (getter && !setter) return
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      childOb = !shallow && observe(newVal)
      dep.notify()
    }

从字面意思也可以看出,就是通知的意思,当我们某个数据进行了变化时,便会触发set劫持,然后dep实例对象会执行它的原型方法notify(),这个方法本质就是把之前通过依赖收集到的并且存放在subs数组中watcher实例进行遍历执行updata()方法,那显而易见updata()方法属于watcher实例对象的原型方法

// Dep
notify () {
  const subs = this.subs.slice()
  。。。
  for (let i = 0, l = subs.length; i < l; i++) {
    subs[i].update()
  }
}

这个updata()方法中进行了三种不同情况的判断,那这里只讲第三种情况queueWatcher(this)

update () {
  /* istanbul ignore else */
  if (this.lazy) {
    this.dirty = true
  } else if (this.sync) {
    this.run()
  } else {
    queueWatcher(this)
  }
}

queueWatcher()大致逻辑也很清晰,它把本次需要更新的watcher实例保存在了一个queue的全局数组中,然后通过nextTick来执行flushSchedulerQueue方法,这也就说明了为什么数据改变后无法直接获取对应的DOM,因为watcher更新放到了异步

文件目录:src/core/observer/scheduler.js

export function queueWatcher (watcher: Watcher) {
  const id = watcher.id
  if (has[id] == null) {
    has[id] = true
    if (!flushing) {
      queue.push(watcher)
    } else {
      // if already flushing, splice the watcher based on its id
      // if already past its id, it will be run next immediately.
      let i = queue.length - 1
      while (i > index && queue[i].id > watcher.id) {
        i--
      }
      queue.splice(i + 1, 0, watcher)
    }
    // queue the flush
    if (!waiting) {
      waiting = true

      if (process.env.NODE_ENV !== 'production' && !config.async) {
        flushSchedulerQueue()
        return
      }
      nextTick(flushSchedulerQueue)
    }
  }
}

flushSchedulerQueue()方法中遍历queue,并且执行watcher实例的before()方法和run()方法,

function flushSchedulerQueue () {
  queue.sort((a, b) => a.id - b.id)
  。。。
  for (index = 0; index < queue.length; index++) {
    watcher = queue[index]
    if (watcher.before) {
      watcher.before()
    }
    id = watcher.id
    has[id] = null
    watcher.run()
    。。。
  }
}

这里这个before()方法之前没有介绍过,这里可以小小的提一嘴,它是在Watcher实例化的时候在外面定义的一个回调函数,作用就是触发beforeUpdata钩子函数,这也就解释的清组件更新时beforeUpdata先执行的原因了,那这个范畴属于生命周期钩子函数的原理了本文不会介绍。

run()方法中可以看到又调用了watcher的原型方法get(),而get()会调用this.getter方法,从而触发组件生成虚拟节点、生成真实DOM的这一步骤,到这里也就实现了数据修改后dep通知watcher,watcher再重新进行组件渲染,最后实现View层的改变。

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

到这里为什么要先进行依赖收集就已经很清晰了,只有先进行了依赖收集,把每个数据的dep和对应的watcher实例关联起来,这样才能在数据变化时,知道要让哪个watcher去更新渲染组件。

总的来说一句话

Vue在实例化时会对data上的数据进行递归生成Observer实例对象和Dep实例对象,并且observer这个过程中给每一项对象通过Object.defineProperty进行数据劫持。在Watcher实例化的时候会进行依赖收集,触发get劫持,使得dep对象的subs数组中存放了对应的watcher实例,当数据进行变化时,会触发set劫持,dep会通知subs数组中的watcher实例进行更新渲染。