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.
Module variables
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 <h2 id="Asynchronous-delay-function">Asynchronous delay function</h2><p>Next is the core <strong>Asynchronous delay function</strong>. The strategies adopted by different Vue versions here are actually different. </p><p><strong>2.6</strong> version prefers using <strong>microtask</strong> as an async deferred wrapper. </p><p><strong>2.5</strong> version is <strong>macrotask combined with microtask</strong>. However, there are minor issues when state changes before redrawing (like #6813). Additionally, using <strong>macrotask</strong> in event handlers can lead to some strange behavior that cannot be circumvented (like #7109, #7153, #7546, #7834, #8109). </p><p>So the <strong>2.6</strong> version is now using <strong>microtask</strong>, why again. . Because <strong>2.4</strong> and earlier versions also use <strong>microtask</strong>. . . </p><p><strong>microtask</strong> There will also be problems in some cases, because <strong>microtask</strong> 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). </p><pre class="brush:php;toolbar:false">// 核心的异步延迟函数,用于异步延迟调用 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!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function