模块
const store = new Vuex.Store({
modules: {
module名字: {
// 每个模块都有自己独立state mutations actions getters 甚至还有modules
state: {},
getters: {},
actions: {},
mutations: {}
}
}
})
命名空间
我们可以给模块对象上添加namespaced: true
const store = new Vuex.Store({
modules: {
module名字: {
namespaced: true
}
}
})
命名空间: 可以给我们的模块的getter mutation action上添加前缀 ‘模块名/’ 便于和其他模块以及root进行区分
state
模块中的state放在rootState下的模块名中 this.$store.state.模块名.属性名
const store = new Vuex.Store({
modules: {
module名字: {
namespaced: true,
state: {
msg: '模块中的数据'
}
}
}
})
// this.$store.state.module名字.msg namespaced属性对state没有任何影响
getters
所有模块的getter都放置在一起,为了区分,我们添加namespaced: true,这个时候,对应模块的getter就变成了 ‘模块名/getter名字’ 使用时
this.$store.getters['模块名/getter名字']
const store = new Vuex.Store({
modules: {
module名字: {
namespaced: true,
getters: {
getter (state, getters, rootState) {
// 只有在模块中的getter中才有第三个参数,rootState可以只从其他模块获取数据 state指的是当前模块的state
}
}
}
}
})
mutations
所有模块的,mutation都放置在一起,为了区分,我们添加namespaced: true,这个时候,对应模块的,mutation就变成了 ‘模块名/,mutation名字’ 使用时
this.$store.commit('模块名/mutation名字')
如果是在action中使用
- 当前模块的action
commit('mutation名字') - 其他模块的action
commit('模块名/mutation名字', null, {root: true})
actions
所有模块的,action都放置在一起,为了区分,我们添加namespaced: true,这个时候,对应模块的,action就变成了 ‘模块名/,action名字’ 使用时
this.$store.dispatch('模块名/action名字')
辅助函数写法
const store = new Vuex.Store({
state: {
a: 1
},
modules: {
moduleA: {
state: {
b: 2,
c: 3
}
}
}
})
export default {
computed: {
...mapState(['a', 'moduleA/b', 'moduleA/c']),
...mapState('moduleA', ['b', 'c'])
}
}