I have this structure for a Vue app: App.vue -> Router View(with two child components)
App.vue
<template>
<div id="app" @click="mutateStore(null)">
<router-view @storeUpdate="mutateStore"/>
</div>
</template>
<script>
export default {
name: 'app',
methods:{
mutateStore(){
this.$store.commit('increment')
}
},
mounted(){
this.$store.commit('increment')
}
}
</script>
<style>
...styles
</style>
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
type: 1
},
mutations: {
increment (state) {
state.type++
}
}
})
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import Main from '@/components/Childcomponent1'
import Display from '@/components/Childcomponent2'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Childcomponent1',
component: Main
},
{
path: '/display',
name: 'Childcomponent2',
component: Display
}
]
})
In Child Component 1, I have a button where if clicked would do:
this.$emit("storeUpdate")
which triggers the event handler mutateStore() in App.vue In Vue Dev Tools, it also shows the state.type with the incremented value
In Child Component 2, I display directly the state.type value as computed:
<template>
<div class="main">
{{type}}
</div>
</template>
<script>
export default {
name: 'Childcomponent2',
computed: {
type () {
return this.$store.state.type
}
}
}
</script>
<style scoped>
..Styles
</style>
But the value never got updated in Child Component 2, not even when viewed in Vue Dev Tools.
And one curious observation, when the same commit in App.vue is called in mounted(), it increments the state.type all across the two child components, but when via method mutateStore(), it does update in Child Component 1, but the change is not detected in Child Component 2.
Note that before I did the emit/event handler part in the App.vue, I already tried mutating the store directly from within the Child Component but to no effect that's why I tried the emit event handler instead.
Did I do anything incorrectly?
Please help!
Found it. Turns out I had wrongly assumed that Vuex standard has built in support for shared states across multiple browser windows using localStorage. Apparently it only does share state across multiple components in the SAME browser tab/window. To allow for multiple browser support, a plugin must be added: vuex-shared-mutations
npm install vuex-shared-mutations