Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a SetTimeout for a message alert component in Vue 3 Composition API?

I am getting started with Vue. I am struggling to create a SetTimeout for a message alert component.

My component looks like this:

<script>
export default {
    name: "Message",
    props: {
        msg: String
    }
}
</script>

<template>
    <div class="alert alert-success mb-2 col-span-3 text-white font-medium">{{ msg }}</div>
</template>

And I’m passing the message through props and trying to get the message and set a time for it to disappear from the screen as below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script setup>
const msg = 'Produto cadastrado com sucesso!'

setTimeout(() => msg = "", 3000)
</script>

<template>
    <MsgAlerts :msg="msg" v-show="msg" />
</template>

>Solution :

The msg should be a reactive data created with ref function in order to respond to any assignment which should be done using .value :

<script setup>
import {ref} from 'vue'
const msg = ref('Produto cadastrado com sucesso!')

setTimeout(() => msg.value = "", 3000)
</script>

<template>
    <MsgAlerts :msg="msg" v-show="msg" />
</template>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading