为了避免不同模块之间的状态、 mutations、actions 和 getters 命名冲突,Vuex 模块可以使用命名空间(namespaced: true)。这样可以确保在访问模块的状态和方法时,需要使用特定的命名空间路径。比如,调用一个命名空间为 “user” 的模块中的 action,可能需要使用
dispatch('user/login')
而不是直接使用dispatch('login')
。
示例
创建带命名空间的模块
const moduleA = {
namespaced: true,
state: {
// 模块 A 的状态
},
mutations: {
// 模块 A 的 mutations
},
actions: {
// 模块 A 的 actions
},
getters: {
// 模块 A 的 getters
}
};
访问命名空间中的状态和方法
1、使用mapState
、mapMutations
、mapActions
和mapGetters
辅助函数时,需要指定模块的命名空间。
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';
export default {
computed: {
// 映射模块 A 的状态
...mapState('moduleA', {
moduleAState: state => state.moduleA.stateProperty,
}),
// 或者使用对象展开运算符更简洁的写法
...mapState('moduleA', {
moduleAState: 'moduleA/stateProperty',
}),
},
methods: {
// 映射模块 A 的 mutations
...mapMutations('moduleA', {
moduleAMutation: 'moduleA/mutationMethod',
}),
// 映射模块 A 的 actions
...mapActions('moduleA', {
moduleAAction: 'moduleA/actionMethod',
}),
// 映射模块 A 的 getters
...mapGetters('moduleA', {
moduleAGetter: 'moduleA/getterMethod',
}),
},
};
2、直接使用$store
访问命名空间模块的状态和方法时,需要使用命名空间路径。
this.$store.dispatch('moduleA/actionMethod', payload);
this.$store.commit('moduleA/mutationMethod', payload);
const stateValue = this.$store.state.moduleA.stateProperty;
const getterValue = this.$store.getters['moduleA/getterMethod'];