我有这个Vue应用程序的结构:App.vue - >路由器视图(带有两个子组件)
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)
})
路由器/ 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
}
]
})
在子组件1中,我有一个按钮,如果单击该按钮将执行:
this.$emit("storeUpdate")
它在App.vue中触发事件处理程序mutateStore()在Vue Dev Tools中,它还显示带有递增值的state.type
在子组件2中,我直接显示计算的state.type值:
<template>
<div class="main">
{{type}}
</div>
</template>
<script>
export default {
name: 'Childcomponent2',
computed: {
type () {
return this.$store.state.type
}
}
}
</script>
<style scoped>
..Styles
</style>
但是,在子组件2中,值永远不会更新,即使在Vue Dev Tools中查看也是如此。
还有一个奇怪的观察,当在mount()中调用App.vue中的相同提交时,它会在两个子组件中增加state.type,但是当通过方法mutateStore()时,它会在子组件1中更新,但是在子组件2中未检测到更改。
请注意,在我在App.vue中执行emit / event处理程序部分之前,我已经尝试直接从Child Component中改变存储,但是没有效果,这就是我尝试使用emit事件处理程序的原因。
我做错了什么吗?
请帮忙!
找到了。事实证明,我错误地认为Vuex标准已使用localStorage在多个浏览器窗口中内置支持共享状态。显然,它只在SAME浏览器选项卡/窗口中跨多个组件共享状态。要允许多个浏览器支持,必须添加一个插件:vuex-shared-mutation
npm install vuex-shared-mutations