Small knowledge, big challenge! This article is participating in the “Essentials for Programmers” creative challenge

Idle time to have a tight mind, busy time to have leisure fun

directory

  • The body of the

    • What is vue.nexttick ()
    • 2. Vue.nexttick () Application scenario
  • conclusion

  • Reference documentation

The body of the

What is vue.nexttick ()

Returns the directory

NextTick ([callback, context]);

grammar

Vue.nextTick([callback, context])

parameter

  • {Function} [callback] : a callback Function that provides a promise call if not passed
  • {Object} [context] : The context in which the callback function is executed. By default, it is automatically bound to the instance calling it.

usage

A deferred callback is performed after the next DOM update loop ends. Use this method immediately after modifying the data to get the updated DOM.

This function is automatically executed when the data is updated and rendered in the DOM.

Here’s an example:

<template> <div class="hello"> <div> <button id="firstBtn" @click="testClick()" ref="firstBtn"> {{ testMsg }} </button> </div> </div> </template> <script> export default {name: 'HelloWorld', data() {return {testMsg: 'not updated ',}; }, methods: {testClick() {this.testmsg = 'updated '; This. TestMsg = 'update again '; This. TestMsg = 'update again '; This. testMsg = 'update again '; This. testMsg = 'update again '; This. testMsg = 'last update '; This.$nextTick(() => {console.log('nextTick callback: ', this.$refs.firstBtn.innerText); // => 'last update'}); $nextTick(). Then () => {console.log('nextTick 'as a Promise: ', this.$refs.firstBtn.innerText); // => 'last update'}); // You want to use the updated DOM immediately. This doesn't work because the DOM doesn't update console.log(' get directly: ', this.$refs.firstbtn.innertext) after message is set; // => 'not updated' console.log(' not doing anything, just playing. '); ,}}}; </script>Copy the code

Click the button and the printed result is:

Direct access: Don't update anything, just play. NextTick callback: Last update nextTick as Promise: last updateCopy the code

It can be found from the above examples:

  1. We changed the value of testMsg several times, but finally only got itThis. testMsg = 'last update';
  2. When the DOM data is retrieved directly after the change, only the pre-update DOM data can be retrieved because the DOM has not been updated yetNot updated
  3. Whether in thenextTickThe callback function, as well as the method in the then function, is executed after all the synchronized code in the current method has been executed, and then the updated DOM data is retrieved

What is the reason for this?

The principle of

JS execution mechanism (Event Loop)

JS Event Loop

JS execution is single threaded and is based on event loops.

  1. All synchronization tasks are executed on the main thread, forming an execution stack.
  2. Outside of the main thread, there is a task queue, and whenever the asynchronous task has a result, an event is placed in the task queue.
  3. When all synchronization tasks in the execution stack are completed, the task queue is read. Those corresponding asynchronous tasks end the wait state and enter the execution stack.
  4. The main thread repeats the third step.

The execution of the main thread is a tick, and all asynchronous results are scheduled through the task queue. Event Loop is divided into macro task and micro task. After the macro task or micro task is executed, the next tick will be entered and UI rendering will be performed between the two ticks.

Vue update policy

Similarly, Vue performs DOM updates asynchronously. The update process is as follows:

  1. Once a change is observed, Vue opens a queue and pushes the watcher that observed the change in the same event loop into the queue.
  2. If the watcher is triggered multiple times, it will only be pushed to the queue once. This buffering behavior effectively eliminates unnecessary computation and DOM manipulation caused by duplicate data.
  3. During the next event loop, Vue empties the queue and performs the necessary DOM updates.

So, when you set this.testMsg = ‘update again ‘; The DOM doesn’t update immediately, and even if you use a for loop to dynamically change the data 100 times, it only applies the last change. The necessary DOM updates occur only after the asynchronous queue is cleared, when the update is performed at the start of the next event loop.

So, to make sure you get the updated DOM, vue.nexttick () is set; Vue.nexttick (callback) can be used immediately after data changes, so that the callback is called after DOM updates are complete.

2. Vue.nexttick () Application scenario

Returns the directory

You need to operate on the new view after the view is updated.

1. Initialize the binding or manipulate the DOM

The CREATED () hook function does not actually render the DOM, and Mounted () does not promise that all children will be mounted at once. DOM manipulation is useless at this point, so if you want to wait until the entire view is rendered, be sure to put the DOM manipulation js code in the view.nexttick () callback.

created() {
    // An error occurs if the this.$nextTick() method is not used
    that.$nextTick(() = > {
        that.$refs.firstBtn.innerHTML = "Created changes button content"; // Write to the DOM element
    });
}
Copy the code

2. Obtain the DOM for data updates

When in a project you want to do something based on the new DOM after changing the DOM element’s data, such as get the V-if controlled DOM node. Must be placed in the vue.nexttick () callback.

<div id="app"> <p ref="myWidth" v-if="showMe">{{message}}</p> <button @click="getMyWidth"> getMyWidth() { this.showMe = true; //this.message = this.$refs.myWidth.offsetWidth; / / error TypeError: This.$refs.myWidth is undefined.$nextTick(()=>{ This. Message = this.$refs.myWidth.offsetwidth; })}Copy the code

3. Third-party plug-ins

When you use a third-party plug-in and want to reapply it when some of the DOM generated by vUE changes dynamically, you need to perform the reapplication of the plug-in in the $nextTick callback. For example, using swiper to request images through Ajax.

conclusion

Returns the directory

The road ahead is long, and I see no end.

Reference documentation

  • Vue. NextTick | Vue website
  • Vue. NextTick () method of use, (simple) | CSDN – wide accumulate grain slow reigns
  • The simple understanding of the Vue nextTick | nuggets – Ruheng
  • Vue $nextTick source code parsing | in Denver – Xie Xiaofei

Postscript: Hello friends, if you think this article is good, remember to give a thumbs-up or star, your thumbs-up and star is my motivation to write more and richer articles!Making the address

Document agreement

Db’s document library is licensed by DB under the Creative Commons Attribution – Non-commercial use – Share alike 4.0 International License. Based on works on github.com/danygitgit. Outside of this license agreement authorized access can be from creativecommons.org/licenses/by… Obtained.

Copy the code