October 6, 2022

Robotic Notes

All technology News

The nextTick function in Vue

1 min read


Feb 23, 2022

The nextTick() function allows you to execute code after you have changed some data and Vue has updated the page to reflect your changes. Pass a callback to nextTick() and Vue will execute the callback immediately after updating the DOM.

const app = new Vue({
  data: () => ({ text: 'First' }),
  template: `<h1>{{text}}</h1>`,
  mounted: function() {
    this.text = 'Second';

    
    console.log(this.$el.textContent);

    this.$nextTick(() => {
      
      console.log(this.$el.textContent);
    });
  }
});

Alternatively, you can use Vue.nextTick()which is the same thing as this.$nextTick().

const app = new Vue({
  data: () => ({ text: 'First' }),
  template: `<h1>{{text}}</h1>`,
  mounted: function() {
    this.text = 'Second';

    
    console.log(this.$el.textContent);

    Vue.nextTick(() => {
      
      console.log(this.$el.textContent);
    });
  }
});

With Promises

One neat advantage of Vue’s nextTick() over the browser’s setTimeout() function is that nextTick() returns a promise, so you can await on it.

const app = new Vue({
  data: () => ({ text: 'First' }),
  template: `<h1>{{text}}</h1>`,
  mounted: async function() {
    this.text = 'Second';

    
    console.log(this.$el.textContent);

    await Vue.nextTick();
    
    console.log(this.$el.textContent);
  }
});

Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!


More View Tutorials



Source link