state - Vuex 不能使用不同的组件
问题描述
我有一个 Vue 应用程序的结构:App.vue -> 路由器视图(有两个子组件)
应用程序.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 开发工具中,它还显示了带有递增值的 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 开发工具中查看也是如此。
一个奇怪的观察是,当在 mount() 中调用 App.vue 中的相同提交时,它会在两个子组件中增加 state.type,但是当通过方法 mutateStore() 时,它会在子组件 1 中更新,但是在子组件 2 中未检测到更改。
请注意,在我在 App.vue 中执行发射/事件处理程序部分之前,我已经尝试直接从子组件中改变存储但没有效果,这就是我尝试使用发射事件处理程序的原因。
我做错了什么吗?
请帮忙!
解决方案
找到了。结果我错误地认为 Vuex 标准已经使用 localStorage 内置了对跨多个浏览器窗口的共享状态的支持。显然,它仅在同一浏览器选项卡/窗口中的多个组件之间共享状态。为了支持多浏览器,必须添加一个插件:vuex-shared-mutations
npm install vuex-shared-mutations
推荐阅读
- python - FileNotFoundError: [Errno 2] No such file or directory: 'Test.csv' in VS Code
- node.js - 为什么我的 Node.js 应用程序构建没有以 heroku 结尾?
- xml - 如何使用 fastxml 将 kotlin 数据类转换为 xml?
- java - 有选择地将事件分派给弹出窗口的子项
- python - Plotly Dash:通过更新不同的下拉组件隐藏/显示滑块组件
- mysql - 为什么喜欢查询和 concat 不使用索引?
- runtime - 使用 AspectJ 进行加载时编织
- ios - 如何在 Swift 5 中限制 iOS App 的文本文件中的复制粘贴?
- r - 运算符在 test_that 函数中不起作用
- firebase - Google Kubernetes Engine 上的 Firebase 授权