Home > Article > Web Front-end > Analysis of nextTick method in Vue2.6
The content of this article is about the analysis of nextTick method in Vue2.6). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
A brief analysis of the nextTick method in Vue 2.6.
Event Loop
JS’s Event Loop and Task Queue are actually the key to understanding the nextTick concept.
There are actually many high-quality articles on this Internet that introduce it in detail, so I just went through it briefly.
The following content applies to browser-side JS. The event loop mechanism of NodeJS is different.
The specification stipulates that tasks are divided into two categories: task(macrotask)
and microtask
.
Task source that is usually considered to be task
:
setTimeout / setInterval setImmediate MessageChannel I/O UI rendering
Task source that is usually considered to be microtask
:
Promise process.nextTick MutationObserver Object.observe(已废弃)
Simple overview : (Here is the official specification)
First start executing the script script until the execution context stack is empty, then start clearing the microtask queue The tasks are queued, first in, first out, each one is executed one after another, and after it is cleared, the event loop is executed.
Event loop: Continuously fetch a task from the task queue and push it into the stack for execution, and execute it in the current loop Clear the tasks in the microtask queue in sequence. After clearing, the page update rendering may be triggered (determined by the browser).
Repeat the event loop steps afterwards.
nextTick
The change of data in Vue to the updated rendering of DOM is an asynchronous process.
This method is used to execute a delayed callback after the DOM update cycle ends.
The method of use is very simple:
// 修改数据 vm.msg = 'Hello'; // DOM 还没有更新 Vue.nextTick(function() { // DOM 更新了 }); // 作为一个 Promise 使用 Vue.nextTick().then(function() { // DOM 更新了 });
The source code, without comments, actually only has less than a hundred lines, and the whole thing is still very easy to understand.
This is divided into 3 parts.
Introduction to imported modules and defined variables.
// noop 空函数,可用作函数占位符 import { noop } from 'shared/util'; // Vue 内部的错误处理函数 import { handleError } from './error'; // 判断是IE/IOS/内置函数 import { isIE, isIOS, isNative } from './env'; // 使用 MicroTask 的标识符 export let isUsingMicroTask = false; // 以数组形式存储执行的函数 const callbacks = []; // nextTick 执行状态 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](); } }
Next is the core Asynchronous delay function. The strategies adopted by different Vue versions here are actually different.
2.6 version prefers using microtask as an async deferred wrapper.
2.5 version is macrotask combined with microtask. However, there are minor issues when state changes before redrawing (like #6813). Additionally, using macrotask in event handlers can lead to some strange behavior that cannot be circumvented (like #7109, #7153, #7546, #7834, #8109).
So the 2.6 version is now using microtask, why again. . Because 2.4 and earlier versions also use microtask. . .
microtask There will also be problems in some cases, because microtask has a higher priority and the event will occur in the sequence of events (such as #4521, #6690 workaround) even fires during bubbling of the same event (#6566).
// 核心的异步延迟函数,用于异步延迟调用 flushCallbacks 函数 let timerFunc; // timerFunc 优先使用原生 Promise // 原本 MutationObserver 支持更广,但在 iOS >= 9.3.3 的 UIWebView 中,触摸事件处理程序中触发会产生严重错误 if (typeof Promise !== 'undefined' && isNative(Promise)) { const p = Promise.resolve(); timerFunc = () => { p.then(flushCallbacks); // IOS 的 UIWebView,Promise.then 回调被推入 microtask 队列但是队列可能不会如期执行。 // 因此,添加一个空计时器“强制”执行 microtask 队列。 if (isIOS) setTimeout(noop); }; isUsingMicroTask = true; // 当原生 Promise 不可用时,timerFunc 使用原生 MutationObserver // 如 PhantomJS,iOS7,Android 4.4 // issue #6466 MutationObserver 在 IE11 并不可靠,所以这里排除了 IE } else if ( !isIE && typeof MutationObserver !== 'undefined' && (isNative(MutationObserver) || // PhantomJS 和 iOS 7.x MutationObserver.toString() === '[object MutationObserverConstructor]') ) { 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; // 如果原生 setImmediate 可用,timerFunc 使用原生 setImmediate } else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { timerFunc = () => { setImmediate(flushCallbacks); }; } else { // 最后的倔强,timerFunc 使用 setTimeout timerFunc = () => { setTimeout(flushCallbacks, 0); }; }
Summary of priorities in one sentence: microtask priority.
Promise > MutationObserver > setImmediate > setTimeout
nextTick function
nextTick function. Accepts two parameters:
cb callback function : is the function to be delayed;
ctx : this of the designated cb callback function points to ;
Vue instance method $nextTick is further encapsulated, and ctx is set to the current Vue instance.
export function nextTick(cb?: Function, ctx?: Object) { let _resolve; // cb 回调函数会经统一处理压入 callbacks 数组 callbacks.push(() => { if (cb) { // 给 cb 回调函数执行加上了 try-catch 错误处理 try { cb.call(ctx); } catch (e) { handleError(e, ctx, 'nextTick'); } } else if (_resolve) { _resolve(ctx); } }); // 执行异步延迟函数 timerFunc if (!pending) { pending = true; timerFunc(); } // 当 nextTick 没有传入函数参数的时候,返回一个 Promise 化的调用 if (!cb && typeof Promise !== 'undefined') { return new Promise(resolve => { _resolve = resolve; }); } }
Summary
Looking at it as a whole, it feels relatively easy to understand~ 2.6 This version is a little simpler than before.
To summarize, what will be done each time Vue.nextTick(cb)
is called:
cb function is processed and pushed into the callbacks array, execute the timerFunc function , delay the call of the flushCallbacks function , and traverse and execute all functions in the callbacks array .
The priority of delayed calls is as follows:
Promise > MutationObserver > setImmediate > setTimeout
Version differences
In fact, the nextTick strategies of Vue 2.4, 2.5, and 2.6 versions are slightly different.
Overall 2.6 and 2.4 are relatively similar. (Take a closer look, it’s basically the same, 2.6 timerFunc has an additional setImmediate judgment)
2.5 The version is actually similar. . . The source code is written a little differently. The overall priority is: Promise > setImmediate > MessageChannel > setTimeout, if the update is in Triggered in the v-on event handler, nextTick will use macrotask first.
The above is the detailed content of Analysis of nextTick method in Vue2.6. For more information, please follow other related articles on the PHP Chinese website!