- 实现思路:
- 可以通过在Vuex的根状态中定义共享状态,然后各个模块通过
getters
、mutations
和actions
来访问和修改这些共享状态。
- 也可以使用Vuex的
module
嵌套结构,将共享状态相关的模块作为一个独立的子模块,各个需要共享状态的模块通过导入这个子模块来实现共享。
- 关键代码步骤(以在根状态定义共享状态为例):
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
sharedState: 'default value' // 在根状态定义共享状态
},
getters: {
getSharedState: state => state.sharedState // 定义getter获取共享状态
},
mutations: {
updateSharedState(state, newVal) {
state.sharedState = newVal; // 定义mutation更新共享状态
}
},
actions: {
updateSharedStateAction({ commit }, newVal) {
commit('updateSharedState', newVal); // 定义action调用mutation更新共享状态
}
},
modules: {
moduleA: {
// moduleA相关代码,可通过根状态访问共享状态
getters: {
getSharedStateInModuleA: (state, getters, rootState) => rootState.sharedState
},
actions: {
updateSharedStateFromModuleA({ rootDispatch }, newVal) {
rootDispatch('updateSharedStateAction', newVal);
}
}
},
moduleB: {
// moduleB相关代码,可通过根状态访问共享状态
getters: {
getSharedStateInModuleB: (state, getters, rootState) => rootState.sharedState
},
actions: {
updateSharedStateFromModuleB({ rootDispatch }, newVal) {
rootDispatch('updateSharedStateAction', newVal);
}
}
}
}
});
export default store;
<template>
<div>
<p>{{ sharedState }}</p>
<button @click="updateSharedState">Update Shared State</button>
</div>
</template>
<script>
export default {
computed: {
sharedState() {
return this.$store.getters.getSharedState;
}
},
methods: {
updateSharedState() {
this.$store.dispatch('updateSharedStateAction', 'new value');
}
}
};
</script>