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(() => {});
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With