Skip to content

响应式系统相关数据结构

数据结构图

1. targetMap

targetMap是一个全局的WeakMap,它的关键特性在于能够自动垃圾回收那些不再使用的对象。targetMap用于存储所有响应式对象及其依赖图。

示例结构:

javascript
targetMap: WeakMap {
  target1: depsMap {
    key1: Set [ effect1, effect2 ],
    key2: Set [ effect3 ]
  },
  target2: depsMap {
    key1: Set [ effect4 ]
  }
}
targetMap: WeakMap {
  target1: depsMap {
    key1: Set [ effect1, effect2 ],
    key2: Set [ effect3 ]
  },
  target2: depsMap {
    key1: Set [ effect4 ]
  }
}

2. depsMap

depsMap是存储在targetMap中针对每个响应式对象的Map,用于跟踪对象各个属性的响应式依赖(副作用函数)。

示例结构:

javascript
depsMap: Map {
  key1: Set [ effect1, effect2 ],
  key2: Set [ effect3 ]
}
depsMap: Map {
  key1: Set [ effect1, effect2 ],
  key2: Set [ effect3 ]
}

3. activeEffect

activeEffect保存了当前正在执行的副作用函数,是Vue用于自动跟踪依赖和决定是否应用更新的重要机制。

示例代码:

javascript
let activeEffect = null

function effect(fn) {
  const effectFn = () => {
    try {
      activeEffect = effectFn
      return fn() // 执行用户传入的fn
    } finally {
      activeEffect = null
    }
  }

  effectFn()
}
let activeEffect = null

function effect(fn) {
  const effectFn = () => {
    try {
      activeEffect = effectFn
      return fn() // 执行用户传入的fn
    } finally {
      activeEffect = null
    }
  }

  effectFn()
}