$nextTick 宏任务 微任务 macrotasks microtasks
Posted mengfangui
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了$nextTick 宏任务 微任务 macrotasks microtasks相关的知识,希望对你有一定的参考价值。
1、nextTick调用方法
首先看nextTick的调用方法:
https://cn.vuejs.org/v2/api/#Vue-nextTick
// 修改数据
vm.msg = ‘Hello‘
// DOM 还没有更新
Vue.nextTick(function () {
// DOM 更新了
})
// 作为一个 Promise 使用 (2.1.0 起新增,详见接下来的提示)
Vue.nextTick()
.then(function () {
// DOM 更新了
})
即:既可以支持回调函数,也可以支持then方法(即Promise)。
2、vue nextTick源码分析
https://github.com/vuejs/vue/blob/dev/src/core/util/next-tick.js
核心代码--nextTick函数:
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
if (useMacroTask) {
macroTimerFunc()
} else {
microTimerFunc()
}
}
// $flow-disable-line
if (!cb && typeof Promise !== ‘undefined‘) {
return new Promise(resolve => {
_resolve = resolve
})
}
}
更核心的代码:
if (!pending) {
pending = true
if (useMacroTask) {
macroTimerFunc()
} else {
microTimerFunc()
}
}
即:nextTick既可以是宏任务,又可以是微任务!
接着看微任务的定义:
// Determine microtask defer implementation.
/* istanbul ignore next, $flow-disable-line */
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
}
即:vue环境支持Promis的话,使用Promise。否则microTimerFunc 被定义为宏任务macroTimerFunc。
接着看macroTimerFunc的定义:
// 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 */
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)
}
}
优先使用setImmediate,其次是MessageChannel,最后是setTimeout。以上三个都属于宏任务。
$nextTick属于宏任务还是微任务,你会了吗?
以上是关于$nextTick 宏任务 微任务 macrotasks microtasks的主要内容,如果未能解决你的问题,请参考以下文章