In this tutorial, we will demonstrate how to show a message in Vue 3 after a delay using the setTimeout method.
First, we import ref and onMounted from vue as follows:
import { ref, onMounted } from "vue";
Code language: JavaScript (javascript)
Next, we create two ref variables: message and displayedMessage.
message will be the input from the user and displayedMessage will be the message that will be displayed after the delay.
const message = ref('')
const displayedMessage = ref('')
Code language: JavaScript (javascript)
We will then create a function called showMessage. In this function, we will first set the displayedMessage to an empty string. We will then use the setTimeout function to wait for 2 seconds before setting the displayedMessage to the message variable.
const showMessage = () => {
displayedMessage.value = ''
setTimeout(() => {
displayedMessage.value = message.value
}, 2000)
}
Code language: JavaScript (javascript)
In our template, we will have an input field that is bound to the message variable using the v-model directive. We will also have a button that, when clicked, will call the showMessage function.
<template>
<div>
<input type="text" v-model="message" />
<div>
<button @click="showMessage">
Show message
</button>
</div>
<div style="margin-top: 20px">
{{ displayedMessage }}
</div>
</div>
</template>
Code language: HTML, XML (xml)
Finally, we will use the double curly brace syntax to display the displayedMessage on the screen.
<div style="margin-top: 20px">
{{ displayedMessage }}
</div>
Code language: HTML, XML (xml)