I am facing an issue with my <v-snackbar>
component not showing when I update the Vuex state.
The setup is straightforward: I have a snackbar in Snackbar.js, which listens for changes in the state.
This Snackbar.js is then imported as a child component in App.vue to make it global.
Subsequently, Test.vue contains a simple button. Upon clicking the button, I expect the State to be updated and the snackbar to render, but it fails to do so.
Upon inspecting the Snackbar component using Chrome Vue Devtools, I noticed that the data does reach the store, but somehow doesn't update the reactive props in Test.vue https://i.sstatic.net/6xzPG.png
Below are the relevant code snippets:
Snackbar.vue
<template>
<v-snackbar v-model="show" :top="top" multi-line rounded="pill">
{{ text }}
<v-btn text @click.native="show = false">
<v-icon>close</v-icon>
</v-btn>
</v-snackbar>
</template>
<script>
import { mapState } from 'vuex'
export default {
data () {
return {
show: false,
text: '',
top: true
}
},
computed: {
...mapState(['snackbar'])
},
created: () => {
this.unwatch = this.$store.watch(
// watch snackbar state
(state, getters) => getters.snackbar,
() => {
const text = this.$store.state.snackbar.text
if (text) {
this.show = true
this.text = text
}
}
)
},
beforeDestroy () {
this.unwatch()
}
}
</script>
App.vue
<template>
<v-app>
<v-main>
<!-- try to set a global snackbar -->
<Snackbar/>
<router-view/>
</v-main>
</v-app>
</template>
<script>
import Snackbar from '@/components/Snackbar'
export default {
name: 'App',
components: {
Snackbar
}
}
</script>
Test.vue
<template>
<v-btn @click="passData">Show snackbar</v-btn>
</template>
<script>
import { mapActions } from 'vuex'
export default {
name: 'Test',
data: () => ({
//
}),
computed: {},
methods: {
...mapActions([
'setSnackbar'
]),
passData () {
this.setSnackbar({
text: 'Simple message',
isActive: true
})
}
}
}
</script>
Store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
snackbar: {
isActive: false,
text: ''
}
},
getters: {
snackbar (state) {
return state.snackbar
}
},
mutations: {
populateSnackbar (state, payload) {
state.snackbar.isActive = payload.isActive
state.snackbar.text = payload.text
}
},
actions: {
setSnackbar (context, payload) {
context.commit('populateSnackbar', payload)
}
}
})