Vue源码学习3.2:依赖收集

675 阅读10分钟

通过上一节的分析我们了解 Vue 会把普通对象变成响应式对象,响应式对象 getter 相关的逻辑就是做依赖收集,这一节我们来详细分析这个过程。

我们先来回顾一下 getter 部分的逻辑:

// src/core/observer/index.js
export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
{
  const dep = new Dep()

  const property = Object.getOwnPropertyDescriptor(obj, key)
  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]
  }

  let childOb = !shallow && observe(val)
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    getfunction 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
    },
    setfunction reactiveSetter (newVal{
      // ...
    }
  })
}

这段代码我们只需要关注 2 个地方:

  • 一个是 const dep = new Dep() 实例化一个 Dep 的实例
  • 另一个是在 get 函数中通过 dep.depend 做依赖收集

还有个对 childOb 判断的逻辑,我们之后会介绍它的作用。

1. Dep

Dep 是整个 getter 依赖收集的核心,它的定义在 src/core/observer/dep.js 中:

// src/core/observer/dep.js

let uid = 0

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

  constructor () {
    this.id = uid++
    this.subs = [] // 用来保存 watcher 的数组
  }

  addSub (sub: Watcher) {
    this.subs.push(sub)
  }

  removeSub (sub: Watcher) {
    // ...
  }

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

  notify () {
    // ...
  }
}

// 全局唯一的 Watcher
Dep.target = null
const targetStack = []

// 设置新的全局 Watcher,并保存上一次的 Watcher
export function pushTarget (target: ?Watcher{
  targetStack.push(target)
  Dep.target = target
}

// 恢复上一次的 Watcher
export function popTarget ({
  targetStack.pop()
  Dep.target = targetStack[targetStack.length - 1]
}

Dep 实际上就是对 Watcher 的一种管理,这里需要特别注意的是它有一个静态属性 target,这是一个全局唯一 Watcher,这是一个非常巧妙的设计,因为在同一时间只能有一个全局的 Watcher 被计算。

2. Watcher

为了完整地讲清楚依赖收集过程,我们有必要看一下 Watcher 的一些相关实现,它的定义在 src/core/observer/watcher.js 中:

// src/core/observer/watcher.js

let uid = 0

/**
 * 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 {
  // 属性声明...

  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  
) {
    this.vm = vm
    if (isRenderWatcher) {
      vm._watcher = this
    }
    vm._watchers.push(this)
    
    // ...
    
    this.deps = [] // 上一次添加的 Dep 实例数组
    this.newDeps = [] // 新添加的 Dep 实例数组
    this.depIds = new Set() // 上一次添加的 Dep id 数组
    this.newDepIds = new Set() // 新添加的 Dep id 数组
    
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } 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) {
      // ...
    } finally {
      // ...
      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
  }

  // ...
}

Watcher 的构造函数中,定义了一些和 Dep 相关的属性:

  • deps:上一次添加的 Dep 实例数组
  • newDeps:新添加的 Dep 实例数组
  • depIds:上一次添加的 Dep id 数组
  • newDepIds:新添加的 Dep id 数组

这里为何需要区分上一次和新添加的,稍后再解释。

Watcher 还定义了一些原型的方法,和依赖收集相关的有 getaddDepcleanupDeps 方法,单个介绍它们的实现不方便理解,需要结合整个依赖收集的过程把这几个方法讲清楚。

3. 过程分析

之前我们介绍当对数据对象的访问会触发他们的 getter 方法,那么这些对象什么时候被访问呢?还记得之前我们介绍过 Vuemount 过程是通过 mountComponent 函数,其中有一段比较重要的逻辑,大致如下:

updateComponent = () => {
  vm._update(vm._render(), hydrating)
}
new Watcher(vm, updateComponent, noop, {
  before () {
    if (vm._isMounted) {
      callHook(vm, 'beforeUpdate')
    }
  }
}, true /* isRenderWatcher */)

当我们去实例化一个渲染 watcher 的时候,首先进入 watcher 的构造函数逻辑,然后会执行它的 this.get() 方法,进入 get 函数:

get () {
  pushTarget(this)
  let value
  const vm = this.vm
  try {
    value = this.getter.call(vm, vm)
  } catch (e) {
    // ...
  } finally {
    // ...
    popTarget()
    this.cleanupDeps()
  }
  return value
}

大概做了这几件事:

  • 执行 pushTarget(this),将 Dep.target 赋值为当前的渲染 watcher 并压栈(为了恢复用)
  • 执行 this.getter,实际上就是 updateComponent,这个稍后分析
  • 执行 popTarget(),将 Dep.target 恢复成上一个状态,因为当前 vm 的数据依赖收集已经完成。
  • 执行 this.cleanupDeps,完成依赖清空,这个稍后在分析

3.1 updateComponent

updateComponent 函数实际上就是执行

vm._update(vm._render(), hydrating)

先执行 vm._render() 方法,因为之前分析过这个方法会生成 渲染 vnode,并且在这个过程中会对 vm 上的数据访问,这个时候就触发了数据对象的 getter

那么每个对象值的 getter 都持有一个 dep,在触发 getter 的时候会调用 dep.depend() 方法,也就会执行 Dep.target.addDep(this)

刚才我们提到这个时候 Dep.target 已经被赋值为渲染 watcher,那么就执行到 addDep 方法:

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(this),那么就会执行 this.subs.push(sub),也就是说把当前的 watcher 订阅到这个数据持有的 depsubs 中,这个目的是为后续数据变化时候能通知到哪些 subs 做准备。

所以在 vm._render() 过程中,会触发所有数据的 getter,这样实际上已经完成了一个依赖收集的过程。

3.2 cleanupDeps

回到 get 函数,最后还会执行 cleanupDeps

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 // 清空
}

考虑到 Vue 是数据驱动的,所以每次数据变化都会重新 render,那么 vm._render() 方法又会再次执行,并再次触发数据的 getters,所以 Wathcer 在构造函数中会初始化 2 个 Dep 实例数组:

  • newDeps 表示新添加的 Dep 实例数组
  • deps 表示上一次添加的 Dep 实例数组。

在执行 cleanupDeps 函数的时候:

  • 遍历旧的 deps,如果新添加的 dep 中没有这个旧的 dep,则移除此旧的 depsubs 数组中 对 Wathcer 的订阅
  • newDepIdsdepIds 交换,清空 newDepIds
  • newDepsdeps 交换,清空 newDeps

那么为什么需要做 deps 订阅的移除呢,在添加 deps 的订阅过程,已经能通过 id 去重避免重复订阅了。

考虑到一种场景,我们的模板会根据 v-if 去渲染不同子模板 ab,当我们满足某种条件的时候渲染 a 的时候,会访问到 a 中的数据,这时候我们对 a 使用的数据添加了 getter,做了依赖收集,那么当我们去修改 a 的数据的时候,理应通知到这些订阅者。

那么如果我们一旦改变了条件渲染了 b 模板,又会对 b 使用的数据添加了 getter,如果我们没有依赖移除的过程,那么这时候我去修改 a 模板的数据,会通知 a 数据的订阅的回调,这显然是有浪费的。

因此 Vue 设计了在每次添加完新的订阅,会移除掉旧的订阅,这样就保证了在我们刚才的场景中,如果渲染 b 模板的时候去修改 a 模板的数据,a 数据订阅回调已经被移除了,所以不会有任何浪费。

3.3 结合例子

我们现在有如下例子:

// App.vue
<template>
  <div>
    <div v-if="flag">
      {{staticMsg}}
    </div>
    <div v-else>
      {{dynamicMsg}}
    </div>

    <button @click="changeMsg">changeDynamicMsg</button>
    <button @click="toggle">toggle</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      staticMsg: 'hello vue',
      dynamicMsg: 123,
      flag: false
    }
  },
  methods: {
    changeMsg() {
      this.dynamicMsg = Math.random()
    },
    toggle() {
      this.flag = !this.flag;
    }
  }
}
</script>

当页面初始渲染时,界面 UI 如图:

此时 dynamicMsg 对应的 dep 已添加了渲染 watcher 的订阅,因此我们每次点击 changeDynamicMsg 的按钮都会触发页面的重新渲染。

当点击 toggle 按钮后,会移除 dynamicMsg 对应的 dep 的渲染 watcher 的订阅

此时再次点击 changeDynamicMsg 按钮时,尽管 dynamicMsg 的数据发生变化,但是却不会触发页面的渲染