Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

vue.nexttick
vuejs
dom

How to use the Vue.nextTick() method in Vue

Educative Team

Overview

In a Vue application, the DOMData Object Model update is always asynchronous. This means that after we’ve made changes to the value of Vue, the Vue queue takes some time to update and render the changes.

What is nextTick()?

The nextTick() method allows us to execute code after we’ve changed some data and Vue.JS has updated the virtual DOM based on our data change, but before the browser has rendered that change on the page.

When to use the nextTick() method

There are some cases when we need to update the rendered DOM after Vue has rendered it. These updates and rendering are performed very quickly, which is why we don’t notice them, but we still have to wait for them to happen. In such cases, we can use the nextTick() method.


Syntax


Vue.nextTick(function () {
  // code ...
})

  • nextTick(): This accepts a callback function that gets delayed until the next DOM update cycle.

Code

Let’s understand how nextTick works with the help of code examples.

Example 1: Without using nextTick()

The example given below includes two messages. These are "First Message" and "Second Message" and are stored in data() and mounted(), respectively.

The mounted() function is part of the Instance LifeCycle Hooks. It is used after the element is mounted or rendered. This is why we see the "Second Message" as output instead of the message stored in data().

The <template> tag is where we define our HTML elements as written below (<p>, <button>, <div>, etc).

Inside the <style> tags, we import the necessary CSS for our program.

#msg {
    font-size: 30px;
    font-family: "Avenir", Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    margin-top: 40px;
    color: #2c3e50;
}

Example 2: Using nextTick()

Now that we know that mounted() has rendered the element, we can use the nextTick() method to update the rendered DOM after Vue has rendered it.

We have a third message stored inside the function callback of nextTick(). Upon execution, we’ll see the "Third Message" being displayed.

#msg {
    font-size: 30px;
    font-family: "Avenir", Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    margin-top: 40px;
    color: #2c3e50;
}

RELATED TAGS

vue.nexttick
vuejs
dom
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring