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.
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 < copies.length; i++) { copies[i](); } }
Asynchronous delay function
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
