nextTick 是 Vue 的核心实现之一,它与 JavaScript 运行机制息息相关,即事件循环机制(Event Loop)。本文将围绕 Event Loop 来分析 nextTick 的实现逻辑。
nextTick 实现原理
Vue 框架对 nextTick 的实现抽取到单独的 JS 文件,其实现逻辑不难理解,代码数在 100 多行左右,下文会一步一步对其进行分析。
从代码的实现来看,大致可分为三部分,分别是:
- 定义函数
flushCallbacks,其作用是通过callbacks队列保存nextTick的回调函数,在下一个tick遍历callbacks,执行回调函数 - 定义函数
timerFunc,它是一个核心函数,其作用在于定义执行任务是微任务还是宏任务,取决于浏览器的支持情况;但是有一点明确的是微任务优先级高于宏任务 - 对外暴露函数
nextTick,也是nextTick触发的核心方法
我们已经知道了核心的实现,那么来看下每一部分具体是如何实现的?
flushCallbacks
// src/core/util/nextTick.js
/* @flow */
/* globals MutationObserver */
import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'
export let isUsingMicroTask = false
const callbacks = []
let pending = false
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
首先定义三个变量:isUsingMicroTask、callbacks 和 pending ,其作用分别是标记定义的任务是否为微任务、用于保存 nextTick 回调函数和确保同一个 tick 函数 timeFunc 只被调用一次。
flushCallbacks 函数的作用是刷新队列 callbacks,对其进行遍历,执行其回调函数,并将 pending 设置为 false,以此可以执行下一个 tick。
timerFunc
// src/core/util/nextTick.js
// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
let timerFunc
// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
p.then(flushCallbacks)
// In problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) setTimeout(noop)
}
isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// Use MutationObserver where native Promise is not available,
// e.g. PhantomJS, iOS7, Android 4.4
// (#6466 MutationObserver is unreliable in IE11)
let counter = 1
const observer = new MutationObserver(flushCallbacks)
const textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
// Fallback to setImmediate.
// Technically it leverages the (macro) task queue,
// but it is still a better choice than setTimeout.
timerFunc = () => {
setImmediate(flushCallbacks)
}
} else {
// Fallback to setTimeout.
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
从代码注释中可以看出,版本 2.5 主要使用宏任务(macrotasks),微任务(microtasks)为辅,但是出现一些问题,甚至有些问题还比较诡异。
那么,在 2.6+ 版本,修改其实现方式,优先采用微任务,其次才采用宏任务,这得取决于浏览器的支持情况。那么,在实现过程中也根据优先级来定义函数 timerFunc,具体如下:
- 微任务:
Promise>MutationObserver - 宏任务:
setImmediate>setTimeout
因此,timerFunc 定义函数时使用微任务宏任务整体优先级如下:
Promise > MutationObserver > setImmediate > setTimeout
nextTick
// src/core/util/nextTick.js
export function nextTick (cb?: Function, ctx?: Object) {
let _resolve
callbacks.push(() => {
if (cb) {
try {
cb.call(ctx)
} catch (e) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
})
if (!pending) {
pending = true
timerFunc()
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
nextTick 是框架对外暴露的一个函数,供开发者调用,其作用是在下一个 tick 执行回调函数。
首先,将传入的回调函数 cb 添加到队列 callbacks 中,其执行条件是根据 pending 来决定。通过调用函数 timerFunc,它们会在下一个 tick 执行 flushCallbacks,遍历队列 callbacks,执行其回调函数,从而实现异步更新的效果。
需要注意的要点是:在 nextTick 实现中没有直接执行回调函数,而是通过队列 callbacks 将其保存起来,其原因在于保证同一个 tick 内执行多个 nextTick,不会开启多个异步任务,而是将这些异步任务压成一个同步任务,在下一个 tick 执行。