nextTick
要理解nextTick,首先理解它的使用场景,通常我们使用nextTick,是为了在DOM更新后做一些操作,比如获取DOM更新后的数据。
<template>
<input ref="input" type="text" v-model="inputContent"/>
</template>
<script>
export default{
// ...
methods: {
// ...
example: function () {
// 修改数据
this.inputContent = 'changed'
// DOM 还没有更新
this.$nextTick(function () {
// DOM 现在更新了
// `this` 绑定到当前实例
console.log(this.$refs['input'].value)
})
}
}
}
</script>
在vue2.1以上的版本中,如果没有提供一个回调函数,nextTick将会返回一个Promise,我们可以这样使用:
this.$nextTick().then()
了解到nextTick的本质是在DOM更新后立即调用回调函数,而DOM的更新是实时的,上面的例子中this.inputContent赋值之后,会进入执行栈中等待执行,在执行完毕后,DOM会被实时更新,但如果执行栈不为空,我们就不能立即获取到DOM更新后的结果。所以我们应该确保执行栈为空之后,再去调用回调函数。
nextTick调用时机
我们了解到nextTick调用回调函数之前,必须确保执行栈为空,通过事件循环机制(Event Loop),可以知道执行栈首先会执行栈内代码(同步代码,可以看做是宏任务),然后会检查微任务队列是否存在任务,存在则执行微任务队列任务,执行完微任务队列中的任务,判断是否存在需要更新视图的操作,存在则由渲染线程去渲染。
即Event Loop运行机制为:宏任务->微任务->渲染->宏任务...
所以确保执行栈为空的方法有两种:
- 将回调函数推入到宏任务队列(由于宏任务是一次只执行一个,而刚推入的宏任务处于队列尾部,所以执行时间较晚)
- 将回调函数推入到微任务队列(由于正在执行栈中的代码可以理解为宏任务,所以微任务会在执行栈为空后立即执行)
微任务有以下几种:
- Promise
- MutationObserver
- Process.nextTick(Node独有)
- Object.observe(废弃
宏任务有以下几种:
- setTimout/setInterval
- I/O,例如HTTP请求、文件读取FileReader等
- setImmediate
- MessageChannel
由于事件循环的机制,我们的优先级应该是微任务>宏任务,而在微任务中,由于MutationObserver在ios有bug,所以在vue2.5以上版本,对MutationObserver进行了Promise的替代,在Vue2.5之前的版本,还是用MutationObserver来实现微任务。所以优先级为Promise>MutationObserver。
在宏任务中,setImmediate就是设计用来将回调函数推入到宏任务队列中的,所以优先使用setImmediate(在node中和高版本浏览器IE/Chrome支持使用)。在不支持setImmediate的情况下,使用MessageChannel(通过postMessage来推入回调)来替代,最后才是setTimeout,这是由于setTimeout即使设置延迟时间为0,还是存在一定的延迟,chrome的最低延迟为4ms,即在4ms之后才会推入宏任务队列。所以优先级为setImmediate>MessageChannel>setTimeout
nextTick源码实现解析
这里是2.5以上的版本实现:
import { noop } from 'shared/util'
import { handleError } from './error'
import { isIOS, isNative } from './env'
const callbacks = []
let pending = false
//依次执行nextTick中的回调
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
// Here we have async deferring wrappers using both microtasks and (macro) tasks.
// In < 2.4 we used microtasks everywhere, but there are some scenarios where
// microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690) or even between bubbling of the same
// event (#6566). However, using (macro) tasks everywhere also has subtle problems
// when state is changed right before repaint (e.g. #6813, out-in transitions).
// Here we use microtask by default, but expose a way to force (macro) task when
// needed (e.g. in event handlers attached by v-on).
// 这里默认使用microTask,但暴露一个方法withMacroTask,来强制使用macroTask
let microTimerFunc
let macroTimerFunc
let useMacroTask = false
// Determine (macro) task defer implementation.
// Technically setImmediate should be the ideal choice, but it's only available
// in IE. The only polyfill that consistently queues the callback after all DOM
// events triggered in the same loop is by using MessageChannel.
/* istanbul ignore if */
//以setImmediate、MessageChannel、setTimeout的优先级顺序来实现macroTask
if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
macroTimerFunc = () => {
setImmediate(flushCallbacks)
}
} else if (typeof MessageChannel !== 'undefined' && (
isNative(MessageChannel) ||
// PhantomJS
MessageChannel.toString() === '[object MessageChannelConstructor]'
)) {
const channel = new MessageChannel()
const port = channel.port2
channel.port1.onmessage = flushCallbacks
macroTimerFunc = () => {
port.postMessage(1)
}
} else {
/* istanbul ignore next */
macroTimerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
// Determine microtask defer implementation.
/* istanbul ignore next, $flow-disable-line */
//以Promise来实现microTask,如果不支持,则直接使用macroTask
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
microTimerFunc = () => {
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)
}
} else {
// fallback to macro
microTimerFunc = macroTimerFunc
}
/**
* Wrap a function so that if any code inside triggers state change,
* the changes are queued using a (macro) task instead of a microtask.
*/
//暴露一个方法,强制使用macroTask
export function withMacroTask (fn: Function): Function {
return fn._withTask || (fn._withTask = function () {
useMacroTask = true
const res = fn.apply(null, arguments)
useMacroTask = false
return res
})
}
//这里做两件事,有回调推入回调到callbacks中,根据useMacroTask来判断执行macroTimerFunc还是microTimerFunc
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) {
//没有回调返回Promise
_resolve(ctx)
}
})
if (!pending) {
pending = true
if (useMacroTask) {
macroTimerFunc()
} else {
microTimerFunc()
}
}
// $flow-disable-line
// 没有回调的情况下,返回Promise
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
这里可以注意到,nextTick首先会将回调存储到callbacks中,而不是立即执行,这是为了保证在同一个tick内,即使多次执行nextTick,也不会开启多个异步任务(不会开启多个宏任务/微任务),而是把这些异步任务都压成一个同步任务(只会开启一个宏任务/微任务去执行),在下一个tick执行完毕。
值得注意的一点是,vue实现双向绑定的桥梁Watcher(通常用来绑定回调函数和被依赖的数据),在调用回调函数前,如果不是设置为同步watcher,也会将watcher的回调函数放到nextTick中执行:
update () {
if (this.computed) {
// ...
} else if (this.sync) {
//如果是同步的,立即调用回调函数(视图更新等操作)
this.run()
} else {
//放入队列中
queueWatcher(this)
}
}
export function queueWatcher (watcher: Watcher) {
// 获取watcherid
const id = watcher.id
if (has[id] == null) {
// 保证只有一个watcher,避免重复
has[id] = true
// 推入等待执行的队列
queue.push(watcher)
// ...省略细节代码
}
// 将所有更新动作放入nextTick中,推入到异步队列
nextTick(flushSchedulerQueue)
}
function flushSchedulerQueue () {
for (index = 0; index < queue.length; index++) {
watcher = queue[index]
//执行绑定回调,获取最新值
watcher.run()
}
}