关于Vue源码观察者的一个困惑
发布于 3 年前 作者 banyungong 1166 次浏览 来自 问答
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利
Watcher类中的一个方法
cleanupDeps () {
    let i = this.deps.length
    while (i--) {
      // 这一个是进行更新将旧的依赖框数组进行更新
      const dep = this.deps[i]
      if (!this.newDepIds.has(dep.id)) {
        // 遍历旧的deps,如果筐中存在的id在新的筐中不存在的话,进行从dep的依赖中删除,如果在newDepIds中不存在的id,则进行删除
        dep.removeSub(this)
      }
    }
    // 将newDepId和depId进行交换,从而避免申请新的内存,先进行id散列表的交换
    let tmp = this.depIds
    this.depIds = this.newDepIds
    this.newDepIds = tmp
    this.newDepIds.clear()  // 将newDepIds散列表进行清空。
    // 进行依赖框的交换
    tmp = this.deps
    this.deps = this.newDeps
    this.newDeps = tmp
    this.newDeps.length = 0
  }

文件的位置在src/core/observer/watcher.js
困惑在于while循环里面将deps中存在的项,如果不在newDeps中存在,那么该项就从deps中进行移除。然后下面由将新旧的依赖数组进行交换,并且将原本是旧的deps(现在是newDeps)清空。我想问的为什么要进行while里面的操作而不是直接进行交换后移除。

回到顶部