Performance: nextTick for DOM update timing
Controls when DOM updates happen after reactive data changes, affecting rendering timing and user interaction smoothness.
this.someData = newValue; this.$nextTick(() => { const height = this.$refs.element.clientHeight; });
this.someData = newValue; // Immediately access DOM that depends on someData const height = this.$refs.element.clientHeight;
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Immediate DOM read after data change | Multiple reads and writes | Multiple forced reflows | High paint cost due to layout thrashing | [X] Bad |
| Using nextTick to wait for DOM update | Batched DOM writes then reads | Single reflow after batch | Lower paint cost, smoother rendering | [OK] Good |
nextTick in Vue?nextTicknextTick schedules code to run after these DOM updates finish, ensuring the page is updated.nextTick in Vue 3 Composition API?nextTick is imported directly from 'vue'.nextTick(() => { ... }) to run code after DOM updates.import { ref, nextTick } from 'vue';
const count = ref(0);
count.value = 1;
console.log(count.value);
nextTick(() => {
console.log(document.getElementById('count').textContent);
});
Assuming the template is <div id="count">{{ count }}</div>.count.value = 1 updates the reactive data immediately, so console.log(count.value) logs 1.nextTick waits for this update, so inside nextTick callback, the DOM shows '1'.import { ref, nextTick } from 'vue';
const visible = ref(false);
visible.value = true;
console.log(document.getElementById('box').style.display);
nextTick(() => {
console.log(document.getElementById('box').style.display);
});
Template: <div id="box" v-if="visible" style="display:block">Box</div>visible.value = true triggers DOM update, but it happens asynchronously after current code.document.getElementById('box') is null or style.display is empty at first log.nextTick, the element exists and style.display is 'block'.showInput changes from false to true. Which is the best way to ensure the input is focused correctly?showInput changes, Vue updates the DOM asynchronously, so the input may not exist immediately.nextTick(() => inputElement.focus()) ensures the input is in the DOM before focusing.Pass the test and this pattern moves unknown