Comprehensive analysis of nextTick in vue
The followingVue.js tutorial column will introduce to you nextTick in vue. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
#vue is a very popular framework. It combines the advantages of angular and react to form a lightweight and easy-to-use mvvm with two-way data binding features. frame. I prefer to use it. When we use vue, a method we often use is this.$nextTick. I believe you have also used it. A common scenario I use is that after obtaining data, when I need to perform the next step or other operations on the new view, I find that the DOM cannot be obtained. Because the assignment operation only completes the change of the data model and does not complete the view update. At this time we need to use the functions introduced in this chapter.
Why use nextTick
Please see the following piece of code
new Vue({ el: '#app', data: { list: [] }, mounted: function () { this.get() }, methods: { get: function () { this.$http.get('/api/article').then(function (res) { this.list = res.data.data.list // ref list 引用了ul元素,我想把第一个li颜色变为红色 this.$refs.list.getElementsByTagName('li')[0].style.color = 'red' }) }, } })
After I obtain the data, I assign it to the list attribute in the data model, and then I I want to reference the ul element to find the first li and change its color to red, but in fact, this will report an error. When executing this sentence, there is no li under ul, which means that the assignment operation just performed is not currently No updates to the view layer are caused.
Therefore, in this case, vue provides us with the $nextTick method. If we want to operate on the updated view in the future, we only need to pass the function to be executed to this.$nextTick method. , vue will do this work for us.
Source code interpretation
This function is very simple, starting from line 450 of vue2.2.6 version.
First of all, does this function use a simple interest mode or is it a closure function created by something?
var callbacks = []; // 缓存函数的数组 var pending = false; // 是否正在执行 var timerFunc; // 保存着要执行的函数
Firstly, some variables are defined for later use. The following is a function
function nextTickHandler () { pending = false; // 拷贝出函数数组副本 var copies = callbacks.slice(0); // 把函数数组清空 callbacks.length = 0; // 依次执行函数 for (var i = 0; i < copies.length; i++) { copies[i](); } }
This function is the function actually called in $nextTick.
Next, Vue divides into three situations to delay calling the above function, because the purpose of $nextTick is to delay the incoming function until the dom is updated before using it, so here we use js in elegant descending order. method to do this.
1. Delayed call of promise.then
if (typeof Promise !== 'undefined' && isNative(Promise)) { var p = Promise.resolve(); var logError = function (err) { console.error(err); }; timerFunc = function () { p.then(nextTickHandler).catch(logError); if (isIOS) { setTimeout(noop); } }; }
If the browser supports Promise, then use Promise.then to delay the function call. The Promise.then method can Delay the function to the end of the current function call stack, that is, the function is called at the end of the function call stack. thereby achieving delay.
2. MutationObserver monitors changes
else if (typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) || MutationObserver.toString() === '[object MutationObserverConstructor]' )) { var counter = 1; var observer = new MutationObserver(nextTickHandler); var textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = String(counter); }; }
MutationObserver is a new function added by h5. Its function is to monitor changes in dom nodes and execute after all dom changes are completed. Callback.
There are several specific changes to monitor
childList: changes in child elements
attributes: changes in attributes
characterData: changes in node content or node text
subtree: changes in all subordinate nodes (including child nodes and child nodes of child nodes)
It can be seen that the above code creates a text node to change the content of the text node to trigger changes, because after we update the data model, it will cause the dom node to re-render. .
So, we added such a change listener, triggering the listener with a change in a text node, and after all dom is rendered, execute the function to achieve our delay effect.
3. setTimeout delayer
else { timerFunc = function () { setTimeout(nextTickHandler, 0); }; }
Using the delay principle of setTimeout, setTimeout(func, 0) will delay the func function to the beginning of the next function call stack. That is, the function is executed after the current function is executed, thus completing the delay function.
Closure function
return function queueNextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { cb.call(ctx); } if (_resolve) { _resolve(ctx); } }); // 如果没有函数队列在执行才执行 if (!pending) { pending = true; timerFunc(); } // promise化 if (!cb && typeof Promise !== 'undefined') { console.log('进来了') return new Promise(function (resolve) { _resolve = resolve; }) } }
The return function is the closure function we actually use. Every time we add a function, we will think of callbacks. Function array is pushed onto the stack. Then monitor whether it is currently being executed, and if not, execute the function. This is easy to understand. The next if is promise.
this.$nextTick(function () { }) // promise化 this.$nextTick().then(function () { }.bind(this))
The second way of writing the above code is not common for us. It directly calls the $nextTick function and then writes the code in promise format. However, this needs to be manually bound in the then, and Vue does not process it internally.
Related recommendations:
2020 front-end vue interview questions summary (with answers)
vue tutorial Recommendation: The latest 5 vue.js video tutorial selections in 2020
For more programming-related knowledge, please visit: Programming Courses! !
The above is the detailed content of Comprehensive analysis of nextTick in vue. 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



You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with <div>. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() => { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.
