vue-nexttick-wait-for-dom-instead-of-settimeout-tip.png
Шаблон кодуVue.js

Vue nextTick(): Wait for the DOM Instead of Guessing with setTimeout()

After changing reactive state, use nextTick() when the next action depends on the updated DOM. Do not guess the update timing with setTimeout().

Vue does not update the DOM synchronously after every reactive state change. If the next line depends on the updated DOM, setTimeout() only guesses when that update may have completed.

Vue provides nextTick() for this case.

Wait for the DOM Instead of Using setTimeout()

До
javascript
function openInput() {    showInput.value = true;     setTimeout(() => {        input.value?.focus();    }, 0);}
Після
javascript
async function openInput() {    showInput.value = true;     await nextTick();     input.value?.focus();}

In this example, changing showInput may render the input through v-if. Immediately after changing the value, Vue may not have updated the DOM yet, so input.value is not guaranteed to be available.

await nextTick() waits for Vue's next DOM update cycle. After that, code can safely work with the element that has just been rendered.

Complete Example with a Template Ref

JAVASCRIPT - nextTick() after a reactive state change
<script setup>import { nextTick, ref } from 'vue'; const showInput = ref(false);const input = ref(null); async function openInput() {    showInput.value = true;     await nextTick();     input.value?.focus();}</script> <template>
nextTick() does not add an arbitrary delay. It waits until Vue has applied the pending DOM update.

When nextTick() Is Actually Needed

  • focus an element that has just appeared through v-if;
  • measure an element after a state change;
  • scroll a container after rendering new content;
  • run an action that directly depends on the updated DOM.

If the code does not depend on the DOM, there is no reason to add nextTick().

When code needs the result of rendering after a state change, do not guess the timing with setTimeout(). Change the state, await nextTick(), and then work with the updated DOM.

#next-tick #vue-js #vue-3 #composition-api #dom #reactivity

Схожі поради

use-to-refs-instead-of-plain-destructing.pngПорада
Переглянути пораду
#vue-js #vue-3 #composition-api #reactivity #to-refs #reactive #javascript