重学Vue源码,根据​​黄轶大佬​​的vue技术揭秘,逐个过一遍,巩固一下vue源码知识点,毕竟嚼碎了才是自己的,所有文章都同步在 公众号(道道里的前端栈) 和 ​github​ 上。

正文

在​​响应式对象​​​里提到,Vue会把普通对象变成一个响应式对象,它的 ​​getter​​ 是用来做依赖收集的,具体这个依赖收集是怎么做的,这篇来过一下。

在把对象变成响应式的过程中有一个 ​​defineReactive​​ 方法:

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,
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
},
// ...
})
}

之前有说到,在访问响应式对象属性的时候会走它的 ​​get​​​,依赖收集是在 ​​get​​​ 中完成的,在这个方法里,首先拿到 ​​getter​​​ 并进行判断之后,拿到一个 ​​value​​​(因为访问某个属性的话肯定得返回它的值),所以方法最终返回了 ​​value​​​,而中间的 ​​Dep.target​​​ 就是依赖收集的过程了,来看下这个 ​​Dep​​ 是干什么的。

Dep

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

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

constructor () {
this.id = uid++
this.subs = []
}

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

removeSub (sub: Watcher) {
remove(this.subs, sub)
}

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

notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}

简单看下大概能看出来它和 ​​Watcher​​​ 有关系,其实它是和 ​​Watcher​​ 中间建立了一个桥梁。

​Dep​​​ 是一个类,有一个静态属性 ​​target​​​,是一个 ​​Watcher​​​,实际上 ​​Dep.target​​​ 就是一个全局的 ​​Watcher​​​,因为在同一时间只能有一个全局的 ​​Watcher​​​ 被计算,所以这个 ​​target​​​ 就是当前正在计算的 ​​Watcher​​​。除了 ​​target​​​ 之外,还有两个私有属性:​​id​​​ 和 ​​subs​​​,​​id​​​ 就是 ​​uid​​​,每次创建一个 ​​Dep​​​ 就会自增一次,​​subs​​​ 就是订阅数据变化的 ​​Watcher​​ 数组。

回到 ​​get​​​,如果有 ​​Dep.target​​​,就会执行一个 ​​dep.depend()​​​,这个小 ​​dep​​​ 在执行 ​​defineReactive​​​ 的时候就已经被实例化了:​​const dep = new Dep()​​​,然后它会在后面调用 ​​depend​​​ 方法,​​depend​​​ 里面会调用 ​​Dep.target.addDep​​​ 方法,也就是调用 ​​Watcher.addDep​​​,接着 ​​get​​​ 里会调用 ​​childOb​​​,这个判断就是 如果 ​​val​​​ 是一个对象,并且它有 childOb 的时候,就调用 ​​childOb.dep.depend()​​​,后面又调用了一个 ​​dependArray​​(这里现值分析dep)。

Watcher

刚才提到一个 ​​depend​​​ 方法里有一个:​​ Dep.target.addDep(this)​​​,就是调用 ​​Watcher.addDep​​​,那这个 ​​addDep​​​ 应该就和 ​​Watcher​​​ 有关了,这个方法定义在 ​​Watcher​​​ 里,代码在 ​​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 {
vm: Component;
expression: string;
cb: Function;
id: number;
deep: boolean;
user: boolean;
computed: boolean;
sync: boolean;
dirty: boolean;
active: boolean;
dep: Dep;
deps: Array<Dep>;
newDeps: Array<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.computed = !!options.computed
this.sync = !!options.sync
this.before = options.before
} else {
this.deep = this.user = this.computed = this.sync = false
}
this.cb = cb
this.id = ++uid // uid for batching
this.active = true
this.dirty = this.computed // for computed 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 = function () {}
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
)
}
}
if (this.computed) {
this.value = undefined
this.dep = new Dep()
} 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) {
if (this.user) {
handleError(e, vm, `getter for watcher "${this.expression}"`)
} else {
throw e
}
} finally {
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value)
}
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的时候有提到过它,​​new Watcher​​​ 除了求值的方法,还定义了 ​​addDep​​​ 和 ​​cleanupDeps​​​ 方法。前面说到,访问数据对象就会触发它们的 ​​getter​​​ 方法,那这些对象在什么时候访问呢?回忆一下之前说过的 ​​mountComponent​​ 函数,在Vue 进行到 mount 的时候会执行这个函数,里面还有一段很重要的逻辑:

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​​​ 函数,首先会执行一个 ​​pushTarget(this)​​:

export function pushTarget (_target: Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = _target
}

实际上就是把 ​​Dep.target​​​ 赋值为当前的渲染wather,并且还定义了一个 ​​targetStack​​​ 数组,如当前有 ​​Dep.target​​​,就放到 ​​targetStack​​​ 里面去,目的是在 ​​pop​​ 的时候也可以获取到。

接着后面又执行了:

value = this.getter.call(vm, vm)

这个 ​​this.getter​​​ 对应就是 ​​updateComponent​​​ 函数,因为在 Watcher的定义里,有一个 ​​this.getter = expOrFn​​​,​​expOrFn​​​ 就是传入的第二个参数,也就是 ​​updateComponent​​​ 方法,也就是说会执行 ​​vm._update(vm._render(), hydrating)​​​,在执行 ​​vm._render​​​ 的时候,会有一个 ​​vnode = render.call(vm._renderProxy, vm.$createElement)​​​,在这一步可以访问到我们模板里定义的数据,此时就可以访问到数据的 ​​getter​​​,也就是访问到 ​​observe​​​ 里的 ​​get​​:

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

然后这里的 ​​Dep.target​​​ 就是渲染watcher,接着在执行 ​​dep.depend​​​ 的时候,就会执行 ​​Dep.target.addDep(this)​​ 了,也就是执行:

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

如果 ​​newDepIds​​​ 没有 ​​id​​​,就 ​​add​​​ 和 ​​push​​​,如果 ​​depIds​​​ 也没有 ​​id​​​,就执行 ​​dep.addSub(this)​​,也就是:

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

就是说在使用render的时候,就会触发数据的 ​​get​​​,就会走 ​​dep.depend()​​​,最终 watcher 就会走 ​​addSub​​​,然后把 ​​Watcher​​​ 添加到 ​​subs​​​ 上,这样就相当于 ​​Watcher​​ 就是数据的订阅者。

捋一遍:进行 ​​vm._render​​​ 方法会生成渲染VNode,这个过程中会对 ​​vm​​​ 上的数据访问,此时就触发了数据对象的 ​​get​​​,然后每一个键值的 get 都带一个 ​​dep​​​,在触发 get 方法的时候会调用这个 ​​dep.depend()​​​ 方法,也就会执行 ​​Dep.target.addDep(this)​​​,此时 ​​Dep.target​​​ 已经被赋值成了 渲染watcher,所以就执行到 ​​addDep​​​ 方法,该方法里面保证了同一个数据不会被添加多次,然后执行 ​​dep.addSub(this)​​​,接着执行 ​​this.subs.push(sub)​​​,这样当前的 ​​watcher​​​ 就订阅到这个数据带的 ​​dep​​​ 的 ​​subs​​ 中了。

所以,在render过程中,就会触发所有数据的 getter,这样就已经是一个依赖收集的过程。

接着执行了一个 ​​popTarget()​​:

Dep.target = targetStack.pop()

也就是把 ​​Dep.target​​​ 恢复到上一个状态,因为当前vm的依赖收集已经完毕了,所以对应的 渲染watcher,也就是 ​​Dep.target​​ 也得回去。

最后执行一个 ​​this.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​​​ 会再次执行,并再次触发数据的 getter,所以 ​​Watcher​​​ 在构造函数里有2个 ​​Dep​​ 数组:

this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()

在执行 ​​cleanupDeps​​​ 的时候,会首先遍历 ​​deps​​​,移除 ​​dep.subs​​​ 数组中的 ​​Watcher​​​ 订阅,然后把 ​​newDepIds​​​ 和 ​​depIds​​​ 交换, ​​newDeps​​​ 和 ​​deps​​ 交换,并把这两个数组清空。


有一种场景,我们的模板会根据 ​​v-if​​ 去渲染不同子模板 a 和 b,当我们满足某种条件的时候渲染 a 的时候,会访问到 a 中的数据,这时候我们对 a 使用的数据添加了 getter,做了依赖收集,那么当我们去修改 a 的数据的时候,理应通知到这些订阅者。那么如果我们一旦改变了条件渲染了 b 模板,又会对 b 使用的数据添加了 getter,如果我们没有依赖移除的过程,那么这时候我去修改 a 模板的数据,会通知 a 数据的订阅的回调,这显然是有浪费的。


总结

某个响应式数据正在触发getter(依赖收集)的时候,收集的就是当前正在计算的watcher,然后把watche作为数据的订阅者,从而形成一种绑定关系,这样在触发setter(派发更新)的时候,可以知道应当通知哪些订阅者去做响应的处理。

我的公众号:道道里的前端栈,每一天一篇前端文章,嚼碎的感觉真奇妙~