Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get next tick within Vue3 setup script

Tags:

vue.js

vuejs3

How do you use the next tick within the setup script in vue3?

<script setup>


const msg = 'Hello!'

this.$nextTick(() => {
   console.log("next tick ... do something")
});

</script>

<template>
  <p>{{ msg }}</p>
</template>

I've used multiple different methods but I can't find one that works outside of the normal script tags.

Another method I tried was.

import Vue from "vue";

Vue.nextTick(() => {});
like image 254
nat Avatar asked Dec 09 '25 20:12

nat


2 Answers

This is how you can use nextTick() in Vue 3.

<script setup>
import { ref, nextTick } from 'vue'

const count = ref(0)

async function increment() {
  count.value++

  // DOM not yet updated
  console.log(document.getElementById('counter').textContent) // 0

  await nextTick()
  // DOM is now updated
  console.log(document.getElementById('counter').textContent) // 1
}
</script>

<template>
  <button id="counter" @click="increment">{{ count }}</button>
</template>

The above code block is from the documentation, where you can also find more information.

like image 115
Mises Avatar answered Dec 12 '25 20:12

Mises


While the answer from Mises is correct, nextTick() can also be used without async/await as follows:

nextTick().then(() => {
    // DOM is now updated
    console.log("Continue here")
}

I would consider this slightly more best practice, as it allows you to work with Promises.

like image 38
jastram Avatar answered Dec 12 '25 19:12

jastram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!