nextTick
vue版本
2.6.11
源码分析(nextTick)
nextTick源码调用过程总结:
init->timerFunc = (Promise/MutationObserver/setImmediate)
初始化阶段为timerFunc的执行方式赋值,一般来说在Windows浏览器环境下运行timerFunc函数的执行方式都会是Promise.then的方式,使用微任务队列的方式。
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve();
timerFunc = function () {
p.then(flushCallbacks);
if (isIOS) {
setTimeout(noop); }
};
isUsingMicroTask = true;
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
var counter = 1;
var observer = new MutationObserver(flushCallbacks);
var textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true
});
timerFunc = function () {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
isUsingMicroTask = true;
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
timerFunc = function () {
setImmediate(flushCallbacks);
};
} else {
timerFunc = function () {
setTimeout(flushCallbacks, 0);
};
}
$nextTick(fn)->callbacks.push(function(){fn.call(this)})->timerFunc()
使用nextTick的源码如下:
function nextTick (cb, ctx) {
console.log('vue nexttick')
var _resolve;
callbacks.push(function () {
// 全局变量callbacks
if (cb) {
try {
cb.call(ctx); // 这里调用回调
} catch (e) {
handleError(e, ctx, 'nextTick');
}
} else if (_resolve) {
_resolve(ctx);
}
});
if (!pending) {
pending