组件的异步更新
我们应该都知道或者听说过组件的更新是异步的,对于nextTick我们也知道它是利用promise将传入的回调函数放入微任务队列中,在函数更新完以后执行,那么既然都是异步更新,nextTick是怎么保证回调会在组件更新后执行,其插入队列的时机又是什么时候?带着这些问题我们去源码中寻找答案。
先回顾一下组件更新的effect:
- const effect = (instance.effect = new ReactiveEffect(
- componentUpdateFn,
- () => queueJob(update), // updata: () => effect.run() 返回值 componentUpdateFn
- // 将effect添加到组件的scope.effects中
- instance.scope // track it in component's effect scope
- ))
在响应式数据发生改变触发effect执行的时候会执行() => queueJob(update)
调度器,所以我们要去看queueJob干了什么
queueJob
- // packages/runtime-core/src/scheduler.ts
- export function queueJob(job: SchedulerJob) {
- if (
- !queue.length ||
- !queue.includes( // queue中是否已经存在相同job
- job,
- isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex
- )
- ) {
- if (job.id == null) {
- // 向queue添加job queue是一个数组
- queue.push(job)
- } else {
- queue.splice(findInsertionIndex(job.id), 0, job)
- }
- // 执行queueFlush
- queueFlush()
- }
- }
queueJob主要是将scheduler添加到queue队列,然后执行queueFlush
queueFlush
- function queueFlush() {
- // isFlushing和isflushPending初始值都是false
- // 说明当前没有flush任务在执行,也没有flush任务在等待执行
- if (!isFlushing && !isFlushPending) {
- // 初次执行queueFlush将isFlushPending设置为true 表示有flush任务在等待执行
- isFlushPending = true
- // resolvedPromise是promise.resolve()
- // flushJobs被放到微任务队列中 等待所有同步scheduler执行完毕后执行
- // 这样就可以保证flushJobs在一次组件更新中只执行一次
- // 更新currentFlushPromise 以供nextTick使用
- currentFlushPromise = resolvedPromise.then(flushJobs)
- }
- }
flushJobs
当所有的同步scheduler执行完毕后,就会去处理微任务队列的任务,就会执行flushJobs回调函数
- function flushJobs(seen?: CountMap) {
- // 状态改为有flush正在执行
- 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
- }
- // console.log(`running:`, job.id)
- // 执行job
- 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)
- }
- }
- }
总结:
组件内当修改响应式数据后,组件更新函数会被放到queue中,然后注册一个微任务,这个微任务负责执行queue中的所有job,所以这时就算我们同步修改多次/多个响应式数据,同一个组件的更新函数只会被放入一次到queue中,等到同步操作结束后才会去执行注册的微任务,组件更新函数才会被执行,组件才会被更新。
nextTick
vue3中nextTick的实现非常简单:
- export function nextTick<T = void>(
- this: T,
- fn?: (this: T) => void
- ): Promise<void> {
- const p = currentFlushPromise || resolvedPromise
- // nextTick回调函数放到currentFlushPromise的微任务队列中
- return fn ? p.then(this ? fn.bind(this) : fn) : p
- }
这里的关键就是currentFlushPromise,如果你足够细心就会发现currentFlushPromise其实在queueFlush中就被赋值了,它正是把执行组件更新函数的任务放入微队列中的promise,所以在此我们拿到currentFlushPromise正好把nextTick接收到的函数回调放到微队列中flushJobs的后面,等到flushJobs执行完成后组件也已经更新完毕,此时正是我们希望去执行nextTick回调的时机!!
以上就是Vue3组件异步更新和nextTick运行机制源码解读的详细内容,更多关于Vue3组件异步更新nextTick的资料请关注w3xue其它相关文章!