I want to make my snackbar to be customizable based on events such success,error and info. Currently in every form , i have to customize based on this code <SnackBar timeout=1200 text="Form Saved Successfully" color="#1DB954" v-model="snackbar"/>
. I think it would be quite troublesome for the team to edit this code in every form. Is it possible to execute this command using event $emit
?
SnackBar.vue
in component folder
<template>
<div >
<v-snackbar v-model="show" top :color="color" :timeout="timeout">
{{ text }}
<template v-slot:action="{ attrs }">
<v-btn color="#191414" text v-bind="attrs" @click="show= false">
Close
</v-btn>
</template>
</v-snackbar>
</div>
</template>
<script>
export default {
props: {
value: {
type: Boolean,
default:''
},
color: {
type: String,
required: false,
default:''
},
text: {
type: String,
required: true,
default:''
},
timeout: {
type: Number,
required: true,
default:''
},
},
computed: {
show: {
get () {
return this.value
},
set (value) {
this.$emit('input', value)
}
}
},
data: () => ({
}),
methods: {
}
}
</script>
Add.vue
file
<template>
<template v-slot:actions>
<v-btn
color="primary"
depressed
@click="submit()"
>
<div>Test</div>
</v-btn>
<SnackBar timeout=1200 text="Form Saved Successfully" color="#1DB954" v-model="snackbar"/>
</template>
</template>
<script/>
import SnackBar from '~/components/SnackBar.vue'
export default {
components: { SnackBar },
data () {
return {
snackbar: false,
}
},
methods: {
submit(){
this.snackbar=true
},
}
}
CodePudding user response:
the most basic way is to implement EventBus
// event-bus.js
import Vue from 'vue';
export const EventBus = new Vue();
//app.vue
import SnackBar from '~/components/SnackBar.vue'
import EventBus from './event-bus.js'
export default {
components: { SnackBar, EventBus },
created() {
EventBus.$on('show-snackbar', this.showSnackbar)
},
data() {
return {
//snackbar: false,
}
},
methods: {
submit() {
//this.snackbar = true
},
showSnackbar(
text,
value,
color = 'default here',
timeout = 'default here'
) {
//show your snackbar component programmatically
},
},
}
and then in desired components where you need snackbar on you just import EventBus and emit event on it like
// some other component
import EventBus from './event-bus.js'
// other imports
export default {
components: { EventBus, /* other components */ },
methods: {
methodWhereSnackbarNeeded() {
//code
EventBus.$emit('show-snackbar', text /*, other params if not default */)
}
}
need to mention that eventbus is not that thing you would use widely - it becoming a mess to debug it very fast, so on vue forums people advising using state manager (vuex for example)
CodePudding user response:
I have answered the same question in link below.
How to display snackbars in Vuetify?
Hope this helps you out.