ChatGPT解决这个技术问题 Extra ChatGPT

What is nextTick and what does it do in Vue.js?

I read the docs, but I still can't understand it.

I know what data, computed, watch, methods do, but what is nextTick() used for in Vue.js?

The key concept to understand is that the DOM is updated asynchronously. When you change a value in Vue, the change is not immediately rendered to the DOM. Instead, Vue queues a DOM update and then, on a timer, updates the DOM. Normally, this happens so fast that it doesn't make a difference, but, at times, you need to update the rendered DOM after Vue has rendered it, which you can't immediately do in a method because the update hasn't happened yet. In those cases, you would use nextTick. Documented here.
Complementing what @Bert said in https://stackoverflow.com/q/47634258/9979046 above, the nextTick() will be used in Unit Tests, when you need to check if a element exists in DOM (HTML), for example, if you get some information on a Axios request.
why do I feel like nextTick is something like const nextTick = (callback, context) => { setTimeout(callback.bind(context), 0); }; ?

t
tony19

It's all about Timing

nextTick allows you to execute code after you have changed some data and Vue.js has updated the virtual DOM based on your data change, but before the browser has rendered that change on the page.

Normally, devs use the native JavaScript function setTimeout to achieve similar behavior, but using setTimeout relinquishes control over to the browser before it gives control back to you (via calling your callback).

Example

Let's say you changed some data; Vue then updates the vDOM based on that data change (the changes are not yet rendered to the screen by the browser).

If you used nextTick at this point, your callback would get called immediately, and the browser would update the page after that callback finished executing.

If you instead used setTimeout, then the browser would have a chance to update the page, and then your callback would get called.

You can visualize this behavior by creating a small component like the following:
(Check this fiddle to see it live)

<template>
  <div class="hello">
    {{ msg }}
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
        msg: 'One'
    }
  },
  mounted() {
      this.msg = 'Two';

      this.$nextTick(() => {
          this.msg = 'Three';
      });
  }
}
</script>

Run your local server. You will see the message "Three" being displayed.

Now, replace this.$nextTick with setTimeout:

setTimeout(() => {
    this.msg = 'Three';
}, 0);

Reload the browser. You will see "Two" before you see "Three".

That's because, with setTimeout:

Vue updated the vDOM to say "Two" Vue gave control to the browser The browser displayed "Two" Callback was called Vue updated the vDOM to say "Three" Vue gave control to the browser The browser displayed "Three"

But with nextTick, we skip steps 2 and 3! Instead of passing over control after the first vDOM update, Vue calls the callback immediately, which prevents the browser from updating until the callback is finished. In this example, that means "Two" is never actually displayed.

To understand how Vue implements this, you need to understand the concept of the JavaScript Event Loop and microtasks.

Once you have those concepts clear(er), check the source code for nextTick.


This answer gave me so much clarity about how and when to use nexttick and when to use setTimeOut. thank you
t
tony19

Next Tick basically allows you to run some code, after the vue has re-rendered the component when you have made some changes to the a reactive property (data).

// modify data
vm.msg = 'Hello'
// DOM not updated yet
Vue.nextTick(function () {
   // this function is called when vue has re-rendered the component.
})
    
// usage as a promise (2.1.0+, see note below)
Vue.nextTick()
   .then(function () {
       // this function is called when vue has re-rendered the component.
    })

From the Vue.js Documentation:

Defer the callback to be executed after the next DOM update cycle. Use it immediately after you’ve changed some data to wait for the DOM update.

Read more about it, here.


update it how? this is what I don't undertand. if I update vm.msg then the dom is already updated because there is a new text ''hello" .. so how can I update it again? can you post a fiddle with an example pls? thanks
okay, I'll edit the answer and I'll try to explain it further.
@hidar you can use it in situations when you have to do multiple updates, but you want to explicitly render each other at different dom cycles
It's not for allowing you to update the DOM per se, but to do anything with it (be it update, read info from it, etc) after it has been affected/modified by changes done by Vue (because you changed a reactive property value, etc).
That was an example to make it simpler.
n
nos nart

To make Pranshat's answer about the difference between using nextTick and setTimeout, more explicit, I have forked his fiddle: here

mounted() {    
  this.one = "One";
     
  setTimeout(() => {
    this.two = "Two"
  }, 0);
      
  //this.$nextTick(()=>{
  //  this.two = "Two"
  //})}
}

You can see in the fiddle that when using setTimeOut, the initial data flashes very briefly once the component gets mounted before adapting the change. Whereas, when using nextTick, the data is hijacked, changed, before rendering to the browser. So, the browser shows the updated data without even any knowledge of the old. Hope that clears the two concepts in one swoop.


D
Dileep Pal

I have created a useful demo in what scenario we can use nextTick in Vuejs, if you want update or run something immediately after your DOM updates, see addMessage function where i am calling another function in which i am using a nextTick function to update scroll to see latest message.

CDN VUE 3

  • {{msg}}