In a Vue application, the
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.
nextTick()
methodThere 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.
Vue.nextTick(function () {
// code ...
})
nextTick()
: This accepts a callback function that gets delayed until the next DOM update cycle.Let’s understand how nextTick
works with the help of code examples.
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; }
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; }
Free Resources