关于cleanDeps的一个疑问

来源:4-6 依赖收集(下)

躁动的胸大肌

2018-10-07

 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
  }

为什么前面遍历了this.deps,去除掉了不在

 if (!this.newDepIds.has(dep.id)) {
        dep.removeSub(this)
      }

后面还要这样处理?

this.deps = this.newDeps
写回答

2回答

鸡肋2016

2019-10-27

if (!this.newDepIds.has(dep.id)) {
       dep.removeSub(this)
     }

因为这个代码的目的是去除 dep中这次是否使用到了(或者说依赖到了)watcher ,如果这次(渲染)没有使用到 这个dep ,那么dep的内容中也去除掉这个watcher ,方便下一次set更新的时候 不再通知这个watcher

0
0

ustbhuangyi

2018-10-07

tmp = this.deps
this.deps = this.newDeps
this.newDeps = tmp

这几行代码的作用是交换 this.deps 和 this.newDeps,目的是更新一下 this.deps,作为每次保存的 deps

0
2
小了个新
懂了,这里的this.deps只是个容器,while里修改的是内部dep和它没关系
2020-03-19
共2条回复

Vue.js 源码深入解析 深入理解Vue实现原理

全方位讲解 Vue.js 源码,进阶高级工程师

4984 学习 · 1037 问题

查看课程