Search code examples
javascriptvue.jsvuejs3vue-composition-apivue-script-setup

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:

<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>