The nextTick function in Vue
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';
// Prints 'First', because Vue hasn't updated the DOM yet
console.log(this.$el.textContent);
this.$nextTick(() => {
// Prints 'Second', because Vue has updated the DOM
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';
// Prints 'First', because Vue hasn't updated the DOM yet
console.log(this.$el.textContent);
Vue.nextTick(() => {
// Prints 'Second', because Vue has updated the DOM
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';
// Prints 'First', because Vue hasn't updated the DOM yet
console.log(this.$el.textContent);
await Vue.nextTick();
// Prints 'Second', because Vue has updated the DOM
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!
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!