关于vue.js:Vue响应式依赖收集原理分析vue高级必备

2次阅读

共计 12466 个字符,预计需要花费 32 分钟才能阅读完成。

背景

在 Vue 的初始化阶段,_init 办法执行的时候,会执行 initState(vm),它的定义在 src/core/instance/state.js 中。在初始化 data 和 props option 时咱们留神 initProps 和 initData 办法中都调用了 observe 办法。通过 observe (value),就能够将数据变成响应式。

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

    if (value === undefined) {observe(value);
    }
  • initData

    observe(data, true /* asRootData */)

指标

  • 了解 Vue 数据响应式原理,理解响应式原理依赖收集的过程
  • 理解在什么阶段会触发依赖收集

源码解读

入口函数:observe

observe 办法定义在 src/core/observer/index.js 中。如果是一个非 VNode 的对象类型的数据,它会尝试给这个值去创立一个 observer 实例,如果创立胜利,返回新的 observer。或者如果 ob 曾经存在了,就会间接返回一个现有的 observer。

/** * 尝试给这个值去创立一个 observer 实例,如果创立胜利,返回新的 observer  * 或者如果值曾经有了,返回一个现有的 observer * @param {*} value  * @param {boolean} asRootData  * @returns Observer | void */
export function observe (value: any, asRootData: ?boolean): Observer | void {if (!isObject(value) || value instanceof VNode) {return}
  let ob: Observer | void
  // 如果 value 曾经有 observer,就返回现有的 observer
  // 否则如果不是服务器渲染,value 是数组或者对象,value 是可扩大的,value 不是 vue 实例,就创立一个新的 observer
  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)
  }
  // 如果是根组件,vmCount 不为 0
  if (asRootData && ob) {ob.vmCount++}
  return ob
}

通过 new Observer(value) 能够给 value 创立一个 observer 实例,那么 Observer 类的定义和作用是什么?在同一个文件下能够看到 class Observer 是如何定义的。

class Observer

Observer 办法定义在 src/core/observer/index.js 中。在它的构造函数中,首先实例化 Dep 对象(次要用来寄存它的 watcher 列表),接着通过执行 def 函数把本身实例增加到数据对象 value 的 ob 属性上,所以存在 ob 属性意味着曾经被察看过。最初判断 value 为数组的状况下,会数组项遍历,给数组的每一项创立一个 observe 实例;如果是对象,那么遍历所有的属性,通过 Object.defineProperty 批改 getter/setters。参考 vue 实战视频解说:进入学习

/** * Observer 类和每个响应式对象关联。* observer 会转化对象的属性值的 getter/setters 办法收集依赖和派发更新。*/
export class Observer {
  value: any;
  dep: Dep;
  vmCount: number; // number of vms that have this object as root $data

  constructor(value: any) {
    this.value = value
    this.dep = new Dep() // 寄存 Observer 的 watcher 列表
    this.vmCount = 0
    def(value, '__ob__', this) // __ob__ 指向本身 observe 实例,存在 __ob__ 属性意味着曾经被察看过
    // 如果是数组
    if (Array.isArray(value)) {// hasProto = '__proto__' in {} 判断对象是否存在 __proto__ 属性
      if (hasProto) {
        // 如果有 __proto__,就将 value.__proto__ 指向 arrayMethods
        protoAugment(value, arrayMethods)
      } else {
        // 否则,就遍历 arrayMethods,将值复制到 value 上
        copyAugment(value, arrayMethods, arrayKeys)
      }
      this.observeArray(value) // 数组项遍历,给数组的每一项创立一个 observe 实例
    } else {this.walk(value) // 遍历所有的属性,批改 getter/setters
    }
  }

  // 遍历所有的属性,批改 getter/setters,这个办法只有在 value 是 object 时调用
  walk (obj: Object) {const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {defineReactive(obj, keys[i])
    }
  }

  // 数组项遍历,给数组的每一项创立一个 observe 实例
  observeArray (items: Array<any>) {for (let i = 0, l = items.length; i < l; i++) {observe(items[i])
    }
  }
}

咱们来看看对于数组和对象,Observe 别离做了什么解决。

Observe 如何解决数组

首先,对于 value 为数组而言,因为 proto 不是规范属性,有些浏览器不反对,比方 IE6-10,Opera10.1,所以须要依据对象是否存在 proto 属性辨别在原型链上增加办法,protoAugment 和 copyAugment 都是在指标对象上增加属性值。

/** * 将 target.__proto__ 指向 src * 拦挡原型链__proto__,来加强指标对象或数组 * @param {*} target  * @param {Object} src  */
function protoAugment (target, src: Object) {
  /* eslint-disable no-proto */
  target.__proto__ = src
  /* eslint-enable no-proto */
}

/** * 遍历 key 属性值列表,将 src 中的 key 属性值逐个定义到 target 的属性中 * 通过定义暗藏属性,来加强指标对象或数组 * @param {Object} target  * @param {Object} src  * @param {Array<string>} keys  */
/* istanbul ignore next */
function copyAugment (target: Object, src: Object, keys: Array<string>) {for (let i = 0, l = keys.length; i < l; i++) {const key = keys[i]
    def(target, key, src[key]) // // 为 target 定义 key 和值
  }
}

在原型链上增加的属性办法 arrayMethods 在 src/core/observer/array.js 能够找到他的定义。实际上 arrayMethods 就是 push pop shift unshift splice sort reverse 七个个办法。这么做的目标是因为要通过 proto 操作数据的原型链,笼罩数组默认的七个原型办法,以实现数组响应式。

Observe 如何解决对象

其次,对于对象而言,会去遍历对象的每个 key,调用 defineReactive(obj, keys[i]) 办法。它会为 obj[key] 创立一个依赖类 dep(会帮这个 key 定义一个 id 和 subs(watcher 订阅者列表) 不便依赖收集)而后再利用 Object.defineProperty 对对象的 get 和 set 办法做了解决。get 拦挡对 obj[key] 的读取操作,set 拦挡对 obj[key] 的写操作。

/** * 在对象上定义一个响应式的属性。* @param {Object} obj  * @param {string} key  * @param {*} val  * @param {*} customSetter  * @param {*} shallow  * @returns  */
export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {const dep = new Dep() // 为 Object 的 key 创立一个依赖类,会帮这个 key 定义一个 id 和 subs(watcher 订阅者列表)

  const property = Object.getOwnPropertyDescriptor(obj, key)
  // 获取 obj[key] 的属性描述符,发现它是不可配置对象的话间接 return
  if (property && property.configurable === false) {return}

  // cater for pre-defined getter/setters
  const getter = property && property.get
  const setter = property && property.set
  if ((!getter || setter) && arguments.length === 2) {val = obj[key]
  }
  // 对 obj[key] 进行察看,保障对象中的所有 key 都被察看
  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) {// 旧的 obj[key]
      const value = getter ? getter.call(obj) : val
      // 如果新老值一样,则间接 return,不跟新更不触发响应式更新过程
      /* 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()
      }
      // setter 不存在阐明该属性是一个只读属性,间接 return
      // #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() // 告诉依赖的观察者更新}
  })
}

能够看到,defineReactive(obj, keys[i]) 中对对象做了解决,不管嵌套的多深,都会 observe(value) 持续察看,在设置了新的值后,也会从新对新值进行察看,让新值也是响应式的。

下面的代码中,在 Observer 类构造函数执行时创立了一个 new Dep(),之后在定义对象的响应式属性时,也为 Object 的 key 创立一个依赖类 const dep = new Dep(),而后在 set 数据值会触发 dep.notify()。那么 Dep 的作用是什么呢?

class Dep

Dep 类的定义在 src/core/observer/dep.js 下。它的构造函数中定义了 id 和一个用于贮存订阅这个 dep 的 watcher 的数组 subs[]。

/** * 一个 dep 对应一个 object.key,每次 key 更新时调用 dep.notify(),* dep 下的 subs 寄存 Watcher 列表,能够调用 dep.notify() 触发 watcher.update() 使 Watcher 列表更新。*/
export default class Dep {
  static target: ?Watcher; // Dep 类的动态属性,能够应用 Dep.target 拜访,内容是 Watcher
  id: number;
  subs: Array<Watcher>; // Watcher 组成的订阅列表

  constructor() {
    this.id = uid++
    this.subs = [] // watcher 订阅者列表}

  // 向订阅者列表中增加一个订阅者 Watcher
  addSub (sub: Watcher) {this.subs.push(sub)
  }

  // 从订阅者列表中删掉一个 Watcher
  removeSub (sub: Watcher) {remove(this.subs, sub)
  }

  // 让全局惟一的 watcher 增加以后的依赖
  depend () {if (Dep.target) {Dep.target.addDep(this)
    }
  }

  // 告诉订阅者列表触发更新
  notify () {// 用 slice() 办法拷贝一个 subs,不影响 this.subs
    const subs = this.subs.slice()
    if (process.env.NODE_ENV !== 'production' && !config.async) {
      // 如果不是运行异步,Watcher 列表不会在调度器中排序,咱们须要去对他们进行排序以确保他们按程序正确的调度
      subs.sort((a, b) => a.id - b.id)
    }
    // 顺次触发 Watcher.update()
    for (let i = 0, l = subs.length; i < l; i++) {subs[i].update()}
  }
}

Dep.target

这里的 Dep.target 就是一个 watcher 实例,在依赖收集时会调用 watcher.addDep(this) 向观察者中增加本人这个依赖。Dep.notify() 会告诉这个依赖的观察者们顺次触发 Watcher.update()。

Dep.target 是以后正在执行的 watcher,同一时间只会有一个 watcher 在执行。

Dep.target = null
const targetStack = []

// 在须要进行依赖收集的时候调用,设置 Dep.target = watcher
export function pushTarget (target: ?Watcher) {targetStack.push(target)
  Dep.target = target
}

// 依赖收集完结调用,设置 Dep.target 为对堆栈中前一个 watcher
export function popTarget () {targetStack.pop()
  Dep.target = targetStack[targetStack.length - 1]
}

class Watcher

Watcher 类定义在 src/core/observer/watcher.js 中。一个组件渲染时创立一个 watcher。
或者一个表达式创立一个 Watcher,当表达式产生扭转时触发调度。

Watcher 的原型办法中和依赖收集相干的办法有 get() addDep() cleanupDep() 等。在 watcher 的构造函数中会调用它的原型办法 get(),它将 Dep.target 指向以后 watcher。

/** * Watcher 解析一个表达式,收集依赖,当表达式产生扭转时触发调度。Watcher 类用于 $watch() api 和指令。*/
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>; // deps 示意上一次增加的 Dep 实例数组
  newDeps: Array<Dep>; // newDeps 示意新增加的 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()}
  // 一些原型办法
  // 以下是定义在 watcher 类原型对象上的办法,用 Watcher.prototype.get() 拜访
  /**   * Evaluate the getter, and re-collect dependencies.   */
  get () {
    // 将 Dep.target 指向以后 watcher
    pushTarget(this)
    let value
    const vm = this.vm
    try {
      // 让 vm 调用 this.getter,并传入 vm 作为参数
      // this.getter = expOrFn
      value = this.getter.call(vm, vm)
    } catch (e) {if (this.user) {handleError(e, vm, `getter for watcher "${this.expression}"`)
      } else {throw e}
    } finally {
      // 如果须要监听对象外部值的变动,那么调用 traverse 办法
      if (this.deep) {traverse(value) // 递归遍历 value 的每个属性,确保每个属性都被监听
      }
      // 以后 vm 的数据依赖收集曾经实现,复原 Dep.target
      popTarget()
      this.cleanupDeps()}
    return value
  }

  /**   * Add a dependency to this directive.   * 增加一个依赖:如果 dep 数组中没有 dep.id,那么触发 dep 订阅以后 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)
      }
    }
  }

  /**   * Clean up for dependency collection.   * 革除依赖收集   */
  cleanupDeps () {
    // 先放弃 deps 和 newDepIds 数量雷同
    let i = this.deps.length
    while (i--) {const dep = this.deps[i]
      if (!this.newDepIds.has(dep.id)) {dep.removeSub(this) // 如果以后 dep 中没有 newDepIds,就移除它的订阅者列表
      }
    }
    // 更新 depIds、deps 为以后的 deps,而后革除 newDepIds 和 newDeps
    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 the value of the watcher.   * This only gets called for lazy watchers.   */
  evaluate () {this.value = this.get()
    this.dirty = false
  }

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

  /**   * Remove self from all dependencies' subscriber list.   * 从所有依赖项的订阅者列表中删除 self   */
  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 初始化时对数据做的解决,调用创立了 observe 实例和 dep 实例。然而并没有提到 watcher 实例是在什么时候创立的。咱们先来看看一些应用 Watcher 的中央。

Watcher 的利用

  • beforeMount
    在 beforeMount 生命周期时,会通过 new Watcher 生成一个渲染 Watcher,它会在页面渲染的过程中拜访每个数据对象的 getter 属性,从而进行依赖的收集。
  • initComputed()
    遍历 computed 中的每个 key,向 computed watcher 列表中新增一个 watcher 实例。
  • initWatch()
    遍历 watch 中的每一个 key,调用 vm.$watch 创立一个 watcher 实例。

何时触发依赖收集?

在 src/core/instance/lifecycle.js 中能够看到,在 beforeMount 阶段实例化了一个 render watcher,并传入一个 updateComponent 的 expOrFn 办法。之后 watcher 调用它的 this.get()。\

callHook(vm, 'beforeMount')

updateComponent = () => {vm._update(vm._render(), hydrating)
}

new Watcher(vm, updateComponent, noop, {before () {if (vm._isMounted && !vm._isDestroyed) {callHook(vm, 'beforeUpdate')
    }
  }
}, true /* isRenderWatcher */)

在 get() 中先调用了 pushTarget(this) 将 Dep.target 指向以后的渲染 watcher。而后调用了 this.getter.call(vm, vm),实际上意味着执行了 vm._update(vm._render(), hydrating)。vm._render() 返回了一个 vnode,vm._update 实现页面更新。在这个过程中会对 vm 上的数据拜访,这个时候就触发了数据对象的 getter。

// this.getter = expOrFn = updateComponent()
value = this.getter.call(vm, vm)

数据的 getter 中触发 dep.depend() 进行依赖收集。

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

当依赖收集实现后会 popTarget(),复原 Dep.target() = null。最初清空这些依赖。

popTarget()
this.cleanupDeps()

数据变动时,如何进行更新?

数据更新时,会执行 setter,首先会对这个新值 newVal observe(newVal),再调用这个属性的 dep.notify() 告诉它的订阅者们进行更新。

总结

  • Vue 初始化时就会通过 Object.defineProperty 拦挡属性的 getter 和 setter,为对象的每个值创立一个 dep 并用 Dep.addSub() 来存储该属性值的 watcher 列表。
  • 触发依赖收集的阶段是在 beforeMount 时,它会为组件创立一个渲染 Watcher,在执行 render 的过程中就会触发对象的 getter 办法,通过 dep.depend() 将订阅者收集起来。艰深的来说,渲染的时候会先解析模板,因为模板中有应用到 data 中的数据,所以会触发 get 操作,从将渲染的 Watcher 对象收集起来,以便在 set 的时候批量更新。
正文完
 0