前提
首先区分模块类型和命名空间类型
(1)主模块(全局命名空间)
(2)子模块(全局命名空间)
(3)子模块(局部命名空间)
一、在vuex外部访问
- 访问state:访问[1]中的时,直接$store.state.name;访问[2][3]中的时,$store.state.模块名.name;即为此时不按命名空间来区分,按模块名来区分
- 访问getters:访问[1][2]中的时,直接$store.getters[‘name’];访问[3]中的时,$store.getters[‘命名空间/name’];即为此时按命名空间来区分,不按模块名来区分
- 通过dispatch访问action:访问[1][2]中的时,直接$store.dispatch(“action”),访问[3]中的时,$store.dispatch(“命名空间/action”);即为此时按命名空间来区分,不按模块名来区分
- 通过commit访问mutation:访问[1][2]中的时,直接$store.commit(“mutation”),访问[3]中的时,$store.commit(“命名空间/mutation”);即为此时按命名空间来区分,不按模块名来区分
二、在vuex内部访问
- state是个对象,不能访问别的模块,只能被别的模块访问
- mutation有个参数[state],state本模块state;只能访问本模块内的state
- getters有四个参数[state,getters,rootState,rootGetters],state本模块state;getters本模块的getter;rootState其他模块的state[如果访问主模块下的state,则直接rootState.name即可;如果访问的是子模块下的state,则rootState.模块名.name],即rootState只按模块名来区分,不按命名空间来区分;rootGetters其他模块的getter[如果访问全局命名空间下的getter,则直接rootGetters.name即可;如果访问的是局部命名空间下的getter,则rootGetter.命名空间.name],即rootGetters不按模块名来区分,只按命名空间来区分;
- action有六个参数[dispatch,commit, state,getters,rootState,rootGetters];后四个参数和上面解释是一样的;前两个参数有点特殊:
(1)dispatch和commit被局部化了,默认访问的是本模快的action和mutation;
(2)当要访问其他模块下的action和mutation时,首先需要看该action所在的模块是全局命名空间还是局部命名空间;
【1】全局命名空间的情况下:如果要访问的模块的命名空间是全局的,则直接dispatch(“action”)或commit(“mutation”);如果要访问的模块的命名空间是局部的,则dispatch(“命名空间/action”)或commit(“命名空间/mutation”)
【2】局部命名空间的情况下:如果要访问的模块的命名空间是全局的,则直接dispatch(“action”,{},{root:true})或commit(“mutation” ,{},{root:true});如果要访问的模块的命名空间是局部的,则dispatch(“命名空间/action”,{},{root:true})或commit(“命名空间/mutation” ,{},{root:true})