0%

vue3组件异步更新和NextTick的运行机制

组件的异步更新

effect

1
2
3
4
5
6
7
// create reactive effect for rendering
const effect = (instance.effect = new ReactiveEffect(
componentUpdateFn, // fn:组件更新实际执行函数
NOOP,
() => queueJob(update), //scheduler: update: () => effect.run() ,相当于执行componentUpdateFn
instance.scope, // track it in component's effect scope
))

queueJob

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const queue: SchedulerJob[] = []

const resolvedPromise = /*#__PURE__*/ Promise.resolve() as Promise<any>
let currentFlushPromise: Promise<void> | null = null

export function queueJob(job: SchedulerJob) {
if (
!queue.length ||
!queue.includes( // queue中是否已经存在相同job
job,
isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex,
)
) {
if (job.id == null) {
queue.push(job)
} else {
queue.splice(findInsertionIndex(job.id), 0, job)
}
queueFlush()
}
}

queueJob 执行主要是将 scheduler 添加到 queue 队列中,然后执行 queueFlush 函数。

queueFlush

1
2
3
4
5
6
7
8
9
function queueFlush() {
// isFlushing和isflushPending初始值都是false
// 说明当前没有flush任务在执行,也没有flush任务在等待执行
if (!isFlushing && !isFlushPending) {
// 初次执行queueFlush将isFlushPending设置为true,表示有flush任务在等待执行
isFlushPending = true
currentFlushPromise = resolvedPromise.then(flushJobs)
}
}

resolvedPromise 就是 promise.resolve(),flushJobs 被放到微任务队列中,等待所有同步任务执行完毕后执行,这样就可以保证flushJobs在一次组件更新中只执行一次。最后,更新 currentFlushPromise 以供 nextTick 使用。

flushJobs

当所有的同步scheduler执行完毕后,就会去处理微任务队列的任务,就会执行flushJobs回调函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
function flushJobs(seen?: CountMap) {
isFlushPending = false
isFlushing = true
if (__DEV__) {
seen = seen || new Map()
}

// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child so its render effect will have smaller
// priority number)
// 2. If a component is unmounted during a parent component's update,
// its update can be skipped.
// 组件更新的顺序是从父到子 因为父组件总是在子组件之前创建 所以它的渲染效果将具有更小的优先级
// 如果一个组件在父组件更新期间被卸载 则可以跳过它的更新
queue.sort(comparator)
// ...
// 先执行queue中的job 然后执行pendingPostFlushCbs中的job
// 这里可以实现watch中的 postFlush
try {
for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
const job = queue[flushIndex]
if (job && job.active !== false) {
if (__DEV__ && check(job)) {
continue
}
callWithErrorHandling(job, null, ErrorCodes.SCHEDULER)
}
}
} finally {
// job执行完毕后清空队列
flushIndex = 0
queue.length = 0

// 执行flushPostFlushCbs 此时组件已经更新完毕
flushPostFlushCbs(seen)

isFlushing = false
currentFlushPromise = null
// some postFlushCb queued jobs!
// keep flushing until it drains.
if (queue.length || pendingPostFlushCbs.length) {
flushJobs(seen)
}
}
}

NextTick

vue3中的nextTick实现非常简单:

1
2
3
4
5
6
7
export function nextTick<T = void, R = void>(
this: T,
fn?: (this: T) => R,
): Promise<Awaited<R>> {
const p = currentFlushPromise || resolvedPromise
return fn ? p.then(this ? fn.bind(this) : fn) : p
}

这里的关键就是 currentFlushPromise,我们仔细看其实发现 currentFlushPromise 在 queueFlush 中就被赋值,它正是把执行组件更新函数的任务放入微队列中的promise,所以在此我们拿到 currentFlushPromise 正好把 nextTick 接收到的函数回调fn放到微队列中 flushJobs 的后面,等到 flushJobs 执行完成后组件也已经更新完毕,此时正是我们希望去执行 nextTick 回调的时机。

注意:我们知道在一个eventloop中,执行完微任务后才进行渲染更新,那nextTick能拿到最新的dom吗?答案是可以的,执行nextTick回调时候,dom已经被修改,只是还没渲染。我们运行下面的例子便可得到答案。

1
2
3
4
5
6
7
8
<div id="count">{{ count }}</div>

const count = ref(0);
count.value++;
nextTick(() => {
// 执行回调时候,虽然dom还没渲染,但dom已经被修改可以获取最新值
console.log('count', document.getElementById('count').innerText); // 1
});

总结

组件内当修改响应式数据后,组件更新函数会被放到queue中,然后注册一个微任务,这个微任务负责执行queue中的所有job,所以这时就算我们同步修改多次/多个响应式数据,同一个组件的更新函数只会被放入一次到queue中,nextTick的回调也会放入到微队列中 flushJobs 的后面,等到同步操作结束后才会去执行注册的微任务,组件更新函数才会被执行(nextTick在此后执行也会获取到最新的dom值),组件也会被更新。