state: {...},
getters: {
profile () {...} // getters['account/profile'] }
},
posts: { // 进一步嵌套命名空间
namespaced: true,
getters: {
popular () {...} // getters['account/posts/popular'] }
}
}
}
}
})
启用了命名空间的getter和action会收到局部化的getter,dispatch和commit。你在使用模块内容时不需要再同一模块内添加空间名前缀,更改namespaced属性后不需要修改模块内的代码。
四、在命名空间模块内访问全局内容(Global Assets)
如果你希望使用全局state和getter,roorState和rootGetter会作为第三和第四参数传入getter,也会通过context对象的属性传入action若需要在全局命名空间内分发action或者提交mutation,将{ root: true }作为第三参数传给dispatch或commit即可。
modules: {
foo: {
namespaced: true,
getters: {
// 在这个被命名的模块里,getters被局部化了
// 你可以使用getter的第四个参数来调用 'rootGetters'
someGetter (state, getters, rootSate, rootGetters) {
getters.someOtherGetter // -> 局部的getter, ‘foo/someOtherGetter'
rootGetters.someOtherGetter // -> 全局getter, 'someOtherGetter'
}
},
actions: {
// 在这个模块里,dispatch和commit也被局部化了
// 他们可以接受root属性以访问跟dispatch和commit
smoeActino ({dispatch, commit, getters, rootGetters }) {
getters.someGetter // 'foo/someGetter'
rootGetters.someGetter // 'someGetter'
dispatch('someOtherAction') // 'foo/someOtherAction'
dispatch('someOtherAction', null, {root: true}) // => ‘someOtherAction'
commit('someMutation') // 'foo/someMutation'
commit('someMutation', null, { root: true }) // someMutation
}
}
}
}
五、带命名空间的绑定函数
前面说过,带了命名空间后,调用时必须要写上命名空间,但是这样就比较繁琐,尤其涉及到多层嵌套时(当然开发中别嵌套太多,会晕。。)
下面我们看下一般写法
computed: {
...mapState({
a: state => state.some.nested.module.a,
b: state => state.some.nested.module.b
}),
methods: {
...mapActions([
'some/nested/module/foo',
'some/nested/module/bar'
])
}
}
对于这种情况,你可以将模块的命名空间作为第一个参数传递给上述函数,这样所有的绑定会自动将该模块作为上下文。简化写就是
computed: {
...mapStates('some/nested/module', {
a: state => state.a,
b: state => state.b
})
},
methods: {
...mapActions('some/nested/module',[










