Sometimes we may want to show some text or notification for a few seconds and then disappear.
We can do that by toggling the visibility of the element for a few seconds. Here’s an example code demonstrating the same:
<script setup>
import { ref } from 'vue'
const textVisible = ref(false)
const showText = () => {
textVisible.value = true
setTimeout(() => {
textVisible.value = false
}, 3000)
}
</script>
<template>
<div>
<button @click="showText">
Sign up
</button>
<h1 v-if="textVisible">
Thanks for signing up!
</h1>
</div>
</template>
Code language: HTML, XML (xml)
In the above code, we have a reactive state named textVisible. On line 20, we show an h1 element if the textVisible property is true. On line 5, we have a method named showText(). This method will set the value of textVisible to true. Then after 3 seconds, it’ll set it’s value back to false. This will make the text visible for 3 seconds.
You can find a working version of the above code from my repo links below: