Search code examples
javascriptvue.jsvuejs2vue-componentvuetify.js

How do I assign a timeout variable to the <v-alert> tag in Vuetify?


I would like to display an alert box which notifies the user about something. I would like it to disappear after 5 seconds even if the user didn't acknowledge it.

I already tried timeout and :timeout attributes but none of those seem to work and according to Vuetify docs they don't even exist in the tag so I'm clueless.

Template:

<div>
      <v-alert
        :value="alert"
        v-model="alert"
        dismissible
        color="blue"
        border="left"
        elevation="2"
        colored-border
        icon="mdi-information"
      >Registration successful!</v-alert>
    </div>

    <div class="text-center">
      <v-dialog v-model="dialog" width="500">
        <template v-slot:activator="{ on }">
          <v-btn color="red lighten-2" dark v-on="on">Click Me</v-btn>
        </template>

        <v-card>
          <v-card-title class="headline grey lighten-2" primary-title>Privacy Policy</v-card-title>

          <v-card-text>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</v-card-text>

          <v-divider></v-divider>

          <v-card-actions>
            <div class="flex-grow-1"></div>
            <v-btn color="primary" text v-if="!alert" @click="dialog = false, alert">I accept</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
</div>

Script:

import Vue from "vue";

export default {
  data() {
    return {
      alert: false,
      dialog: false
    };
  },

  created() {
    setTimeout(() => {
      this.alert = false
    }, 5000)
  }
};

Solution

  • In created hook add timeout range with 5s that update alert property with false:

    new Vue({
      el: '#app',
      vuetify: new Vuetify(),
      data(){
        return{
           alert: true,
        }
      },
      created(){
        setTimeout(()=>{
          this.alert=false
        },5000)
      }
    })
    

    in template bind v-alert's value prop to alert data property :

    <div id="app">
      <v-app id="inspire">
        <div>
          <v-alert type="success" :value="alert">
            I'm a success alert.
          </v-alert>
    
        </div>
      </v-app>
    

    check this pen