通过 modules 创建 vuex 的模块、子模块中 state getters mutations actions 的访问/调用语法
模块拆分:
1. 在 store 文件夹下再新建文件夹 modules,在 modules 下新建 xxx.js 文件:
eg:新建 user.js 文件
const state = {
userInfo: {
name: 'zs',
age: 18
},
score: 80
}
const mutations = {}
const actions = {}
const getters = {}
export default {
state,
mutations,
actions,
getters
}
2. 在 store 文件夹下的 index.js 文件内引入 user.js:
① import user from './modules/user.js'
②:
const store = new Vuex.Store({
modules: {
user
}
})
------------------------------------------------------------------------------------------------------------------------
模块中 state 的访问语法:
尽管已经分模块了,但其实子模块的状态还是会挂到根级别的 state 中,属性名就是模块名
使用模块中的数据:
1. 直接通过模块名访问:
$store.state.模块名.xxx
2. 通过 mapState 映射
--------------------------------------------------------------------------------------------------------------------------
模块中 getters 的访问语法
使用模块中 getters 中的数据:
1. 直接通过模块名访问:
$store.getters [ ' 模块名 / xxx ' ] // xxx:getters 中的方法名
2. 通过 mapGetters 映射
---------------------------------------------------------------------------------------------------------------------------
模块中 mutation 的调用语法
注意:默认情况下,模块中的 mutation 和 actions 会被挂载到全局,需要在子模块中开启命名空间 才会挂载到子模块:
export default {
namespaced : true,
state,
mutations,
actions,
getters
}
调用子模块中的 mutation:
1. 直接通过 store 调用:
this.$store.commit ( ' 模块名 / xxx ' , 额外参数 ) // xxx:子模块中 mutations 里的方法名
2. 通过 mapMutations 映射
---------------------------------------------------------------------------------------------------------------------------------
模块中 action 的调用语法
注意:默认情况下,模块中的 mutation 和 actions 会被挂载到全局,需要在子模块中开启命名空间 才会挂载到子模块:
export default {
namespaced : true,
state,
mutations,
actions,
getters
}
调用子模块中的 action:
1. 直接通过 store 调用:
this.$store.dispatch ( ' 模块名 / xxx ' , 额外参数 ) // xxx:子模块中 actions 里的方法名
2. 通过 mapActions 映射
浙公网安备 33010602011771号