nextTick allows us to wait untill the DOM has updated and then do something. In the Options API, we could access the nextTick through the global option this.$nextTick. However, this doesn’t work in the Composition API anymore. To access nextTick in the Composition API, you’ll first have to import it from vue and then use it as needed.
Let’s look at an example where we allow the user to enter some input text. Then, when they press the Enter key, we set the entered text as the h2 element value in the app.
<script setup>
import { reactive, nextTick } from "vue";
const inputData = reactive({
inputText: null,
inputHeader: null
})
const onEnter = () => {
inputData.inputHeader = inputData.inputText
nextTick(() => {
console.log('DOM updated!')
})
}
</script>
<template>
<div>
<h2>{{inputData.inputHeader}}</h2>
<input type="text" v-model="inputData.inputText" @keyup.enter="onEnter" placeholder="Enter text" />
</div>
</template>
Code language: HTML, XML (xml)
As you can see in the above code, we first update the inputData.inputText value through the v-model. We then copy its value to inputData.inputHeader as did on line 11. After that, once the DOM is updated, we console logged the message ‘DOM updated!’.
We can also use an async method (in case we don’t know how long it’ll take to process the instruction). We can then await the nextTick and do stuff after that. Here’s an example of how the above code would work with an async call:
const onEnter = async () => {
inputData.inputHeader = inputData.inputText
await nextTick()
console.log('DOM updated!')
}
Code language: JavaScript (javascript)
If you have any doubts or suggestions, sound off in the comments below!