1
votes

I'm new to Vue I wanted to reuse the snackbar / alert box from vuetify to each of my components. I did it by copy pasting the code for each component which makes it very messy and hard to maintain.

How do I reuse this for each of my view vue component?

Please see my example code below.

Vue component < template >

 <v-snackbar
  v-model="snackbar.appear"
  :color="snackbar.color"
  :timeout="snackbar.timeout"
  :left="snackbar.x === 'left'"
  :right="snackbar.x === 'right'"
  :top="snackbar.y === 'top'"
> 
  <v-row>
    <v-icon class="mx-2" size="18" dark>{{ snackbar.icon }}</v-icon>
    {{ snackbar.text }}
  </v-row>
  <v-btn dark text @click="snackbar.appear = false">OKAY</v-btn>
</v-snackbar>

Vue component < script >

snackbar: {
    appear: false,
    icon: '',
    text: '',
    color: 'success',
    timeout: 2500,
    x: 'right',
    y: 'top',
  },

axios 
.post('/api/department-objective', { corporate_objective_id, objective, description })
.then(response => {
  this.snackbar.appear = true
  this.snackbar.text = response.data.text
  this.snackbar.icon = response.data.icon
})
.catch(error => {
  console.log(error)
  this.alert = true
  this.allerror = error.response.data.errors
})
4

4 Answers

5
votes

I often add application wide alert messages to the root application's component, like e.g. an App component building up the base layout and bind it's visibility to the presence of an error or notification property in a central vuex store.

See this answer for details

1
votes

You can create a snackbar component , which you can import in App.vue so that it's available to the every component , you can then trigger this component using vuex store as per you're requirement.

Here's an article which I used while learning to implement the same. How to create a global snackbar using Nuxt, Vuetify and Vuex..

If you dont want to use nuxt , just refer to the article and you'll get the idea.

0
votes

you can create a SnackBarComponent and import it on every other Component

App.vue

<template>
<SnackBarComponenent :stuffProp="yourProps" />
</template>
<script>
import SnackBarComponenent from './components/SnackBarComponent'
export default {
    components:{
        ProfileOverview
     }
}
</script>
0
votes

Here's my implementation with Composition API using provide/inject and a snackbar composable:

https://gist.github.com/wobsoriano/2f3f0480f24298e150be0c13f93bac20

<script lang="ts">
import { defineComponent } from 'vue/composition-api';
import { useSnackbar } from '~/composables';
export default defineComponent({
  setup() {
    const createSnackbar = useSnackbar();
    const showSnackbar = () => {
      createSnackbar('Your snackbar message');
    };
    return {
      showSnackbar
    };
  },
});
</script>