[Vue Interview Questions] Tell me about the use and principle of nextTick?

analyze

This question and the use of investigations have an investigation principle. NextTick is rarely used in the development process. In principle, it is closely related to the asynchronous update of vue. It is very different for the interviewer. If you can answer this question well, yes The interview effect is very helpful.

Answer ideas

  1. What does nextTick do?
  2. Why is it needed?
  3. When do you use it in development? Scratch your head and think about where you use it in normal development
  4. Here's how to use nextTick
  5. Interpretation of the principle, combined with asynchronous update and nextTick effective method, will make you look exceptionally good

Sample answer:

  1. nextTick is a tool method to wait for the next DOM update refresh. (In fact, $nextTick can be explained clearly in one sentence: the operation you put in $nextTick will not be executed immediately, but will be executed after the data update and DOM update are completed, so that what we get must be the latest Yes.
    To be more precise, the $nextTick method delays the execution of the callback until the next DOM update cycle. (If you don’t understand this sentence, you can read it above)

  2. Vue has an asynchronous update strategy, which means that if the data changes, Vue will not update the DOM immediately, but will open a queue and save the component update function in the queue. All data changes that occur in the same event loop will be updated asynchronously in batches . This strategy leads to the fact that our modification of the data will not be reflected on the DOM immediately. At this time, if we want to get the updated DOM state, we need to use nextTick.

  3. During development, we will use nextTick in two scenarios

    • When you want to get DOM in created;
    • Get the updated state of the DOM after the responsive data changes, for example, you want to get the updated height of the list.
  4. type of nextTick

function nextTick(callback?: () => void): Promise<void>

So we only need to access the latest DOM state in the callback function passed in, or we can do this after awaiting the Promise returned by the nextTick() method.

  1. Inside Vue, the reason why nextTick allows us to see the updated DOM is because the callback we pass in will be added behind the queue refresh function (flushSchedulerQueue), so that all the update functions inside the queue are executed. The DOM operation is over, and the callback can naturally get the latest DOM value.

Let's take a look at the official case:

<script>
import {
    
     nextTick } from 'vue'

export default {
    
    
  data() {
    
    
    return {
    
    
      count: 0
    }
  },
  methods: {
    
    
    async increment() {
    
    
      this.count++

      // DOM 还未更新
      console.log(document.getElementById('counter').textContent) // 0

      await nextTick()
      // DOM 此时已经更新
      console.log(document.getElementById('counter').textContent) // 1
    }
  }
}
</script>

<template>
  <button id="counter" @click="increment">{
    
    {
    
     count }}</button>
</template>

Given a count, I want to bind and display it in the interface. It is 0 at the beginning. If the user clicks increment, we hope that the count can be ++, and we hope that the interface can become 1, but you will find that it has not been updated in the following console.log, and the result is still 0, and Not 1, so how to output 1? await nextTick(), and the output result will be 1 later. Why is this so? This is the most critical thing that nextTick() brings us. To put it bluntly, nextTick() will return a promise, and we will call our line of code asynchronously in the future. That is to say, when the console.log under nextTick() is executed in the future, our DOM has been updated. Another way is to add a callback function in the middle of nextTick(), and output the line of code in our console.log in the callback function. This is also possible.

For specific source code analysis, please refer to the interview question: Principle of $nextTick in Vue : It is very clear
. To sum up: $nextTick puts the callback function in the microtask or macrotask to delay its execution sequence;

It is important to understand the meaning of its three parameters in the source code:

  • callback: The operation we want to perform can be placed in this function. We will put the callback function into an asynchronous queue without executing $nextTick once;
  • pending: identification, used to determine whether it is the first time to join in a certain event loop, and the asynchronously executed queue mount is triggered only when the first time is joined
  • timerFunc: used to trigger the execution of the callback function, that is, the process of Promise.then or MutationObserver or setImmediate or setTimeout

After understanding, looking at the entire execution process in $nextTick, it is actually pressing the callback functions in $nextTick into the callback queue one by one, and then waiting for execution according to the nature of the event. When it is its turn to execute, execute it. Then remove the corresponding event in the callback queue.

interview board

Tell me about nextTick

nextTick: A delayed callback to execute after the next DOM update cycle ends.

Does nextTick know?

To expand this sentence, it is because the DOM update in Vue is "asynchronously executed", that is, when the data is modified, the view will not update immediately, but will monitor the data change and cache it in the same event loop, which is equivalent to the same data After all the data changes in the loop are completed, the view is updated uniformly. Often we use an element before it has been updated, so we cannot get the changed dom, so in order to ensure that we can get the updated DOM, we set the nextTick() method. Use this method immediately after modifying the data to get the updated DOM. In a nutshell, nextTick in vue is mainly used to deal with the problem that the DOM has not been updated in time after the data changes dynamically. NextTick can be used to obtain the latest dom changes after the data is updated.

When is it used in the project?

For example, when we need to perform some DOM operations in the created() function of the life cycle, we must put the relevant code in the callback function of Vue.nextTick(). Reason: In the created hook function, the DOM has not been rendered yet, and it is useless to perform DOM operations at this time, so if you want to operate the dom here, you must put the relevant js code into the Vue.nextTick callback function
. Or, when an action needs to be performed after the data changes, and this action needs to use the DOM structure that changes with the data change, it is also necessary to write the relevant logic into the Vue.nextTick () callback function.

Since $nextTick has turned the method it passes into a microtask, what is the execution order of it and other microtasks?

This is simply a question of who mounts the Promise object first. When calling the $nextTick method, the execution queue maintained inside its closure will be mounted to the Promise object. When the data is updated, Vue will first execute the $nextTick method , and then mounted the execution queue on the Promise object. In fact, after understanding the Event Loop model of Js, the data update is also regarded as a call of the $nextTick method, and the $nextTick method will execute all pushed callbacks at one time. , you can understand the problem of execution order.

The difference between $nextTick and nextTick

The difference between $ nextTick and nextTick is that nextTick has an additional context parameter to specify the context. But the essence of the two is the same, $nextTick is an instance method, and nextTick is just a static method of the class; one advantage of the instance method is that it is automatically bound to the this of the calling instance for you.

Guess you like

Origin blog.csdn.net/qq_40992225/article/details/126472625