[Vuejs]-How to change state in vuex after some time while snackbar closes automatically

1👍

I had the same problem preparing a Snackbar component and I used a watcher to change the $state before “timeout” finished. By default, after 6 seconds the snackbar closes but I am using setTimeout with 4 second to modify the State and close it before this 6 seconds.
In my case I am using ts but I think you can use it.

Snackbar component

<template>
  <div>
    <v-snackbar v-model="snackbarData.show"  :color="snackbarData.color" bottom >
      {{snackbarData.message}} 
    </v-snackbar>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Watch, Prop } from "vue-property-decorator";

@Component({})
export default class SnackBar extends Vue {

@Prop({default:null})    
snackbarData!: Object 

 @Watch("snackbarData.show", { deep: true })
  onShowChanges(value: any) {
    if (value === true) {
      const snackbar: any = {
        show: false,
        message:'',
        color: null, 
     };
    setTimeout( () => {
      this.$store.commit('updateMainSnackbar', snackbar);
      }, 4000)
  } 
  }
}

Stored

This is my object but if you need more properties you should add them.

   mainSnackbar: {
        show: false,
        message: '',
        color: null
    }

Mutation

  updateMainSnackbar (state:any, data: any){
      state.mainSnackbar.show = data.show;
      state.mainSnackbar.message = data.message;
      state.mainSnackbar.color = data.color;
    }

Import and Include the component

Import the component and pass the properties

<template>
   <SnackBar :snackbarData="mainSnackbar" />
</template>

// ----------
<script lang="ts">
import Vue from "vue";
import { Component } from "vue-property-decorator";

import SnackBar from "SnackBar.vue"
@Component({
  components: { SnackBar }
})
export default class OurComponent extends Vue {

// Computed

 get mainSnackbar(){
    return this.$store.state.mainSnackbar;
  }

Execute the mutation to active the Snackbar

Call the mutation with the data you want to show in the snackbar. In my case I was using a method.

setSnackBar(){
  const data= {
        show: true,
        message:'The message you want to show',
        color: '#ffff', 
     };
  this.$store.commit('updateMainSnackbar', data);
}

I hope it can help you.

-1👍

Can you watch snackbar in Snackbar component?

something like:

watch: {
  snackbar: function(newVal) {
    if (!newVal) {
       this.snackbarClose()
    }
  }
}
👤ittus

Leave a comment