/store/snackbar.js
[code]
export const state = () => ({
message: ”,
color: ”,
})
export const mutations = {
showMessage(state, payload) {
state.message = payload.message
state.color = payload.color || ‘primary’
},
}
[/code]
/plugins/snackbar.js
[code]
export default ({ app, store }, inject) => {
inject(‘snackbar’, {
showMessage({ message = ”, color = ” }) {
store.commit(‘snackbar/showMessage’, { message, color })
},
})
}
[/code]
/components/Snackbar.vue
[code]
<template>
<v-snackbar v-model=”show” :color=”color” :timeout=”timeout”>
{{ message }}
<template v-slot:action=”{ attrs }”>
<v-btn text v-bind=”attrs” @click=”show = false”> Close </v-btn>
</template>
</v-snackbar>
</template>
<script>
export default {
data() {
return {
show: false,
message: ”,
color: ”,
timeout: 2000,
}
},
created() {
this.$store.subscribe((mutation, state) => {
if (mutation.type === ‘snackbar/showMessage’) {
this.message = state.snackbar.message
this.color = state.snackbar.color
this.show = true
}
})
},
}
</script>
[/code]
store.subscribe() 함수는 mutaion 이 작동할때 후킹이 가능하도록 해주는 함수이다.
/nuxt.config.js
[code]
plugins: [
{ src: ‘~/plugins/snackbar.js’, ssr: false },
],
[/code]
사용하기
[code]
<template>
<div>
<button @click=”doTest”>클릭</button>
</div>
</template>
<script>
export default {
methods: {
doTest() {
this.$snackbar.showMessage( { message: ‘스낵바테스트’, color: ‘info’ })
}
}
}
</script>
[/code]