Sometimes Vue updates the page a little later after you change data. nextTick helps you wait for that update to finish before doing something else.
0
0
nextTick for DOM update timing in Vue
Introduction
You want to run code right after Vue changes the page but before the user sees it.
You need to measure or change something on the page after Vue updates the content.
You want to focus an input box after it appears on the page.
You want to make sure animations start after the page updates.
You want to avoid errors from trying to access elements before they exist.
Syntax
Vue
import { nextTick } from 'vue'; nextTick(() => { // code to run after DOM updates });
nextTick is a function you import from Vue.
You give it a function that runs after Vue finishes updating the page.
Examples
This logs a message after Vue updates the page.
Vue
import { nextTick } from 'vue'; nextTick(() => { console.log('DOM updated'); });
We change a value to show something, then wait for the page to update before running code.
Vue
import { ref, nextTick } from 'vue'; const show = ref(false); show.value = true; nextTick(() => { console.log('Now the element is visible'); });
After showing an input box, we wait for the DOM update, then focus it.
Vue
import { ref, nextTick } from 'vue'; const visible = ref(false); const inputRef = ref(null); function showInput() { visible.value = true; nextTick(() => { inputRef.value?.focus(); }); }
Sample Program
This Vue component shows a button. When clicked, it shows an input box and then focuses it. The nextTick ensures the input exists before focusing.
Vue
<template>
<div>
<button @click="showInputBox">Show Input</button>
<input v-if="visible" ref="inputBox" placeholder="Type here" />
</div>
</template>
<script setup>
import { ref, nextTick } from 'vue';
const visible = ref(false);
const inputBox = ref(null);
function showInputBox() {
visible.value = true;
nextTick(() => {
inputBox.value?.focus();
});
}
</script>OutputSuccess
Important Notes
Without nextTick, trying to focus the input right after changing visible might fail because the input is not yet in the page.
nextTick returns a Promise if you want to use await instead of callbacks.
Summary
nextTick waits for Vue to finish updating the page before running code.
Use it when you need to work with the updated page elements right after data changes.
It helps avoid errors and makes your app feel smooth and responsive.