由于使用单一状态树 应用的所有状态会集中到一个比较大的对象 当应用变得非常复杂时 store对象就可能变得十分臃肿 Vuex就会变得越来越难以维护
由此 有了Vuex的模块化
我们以 用户信息(user) 和 设置(setting) 为例介绍Vuex的模块化
模块定义
定义两个模块
在store/index.js文件中的modules配置项中 注册这两个模块
使用模块中的数据, 可以直接通过模块名访问
$store.state.模块名.xxx
= > $store.state.setting.desc
也可以通过 mapState 映射
获取数据
尽管已经分模块了 但子模块的状态还是会挂到根级别的state中 属性名就是模块名
1.使用state中数据
(1) 直接通过模块名访问
(2) 通过mapState映射
默认根级别映射 mapState( [ ‘xxx’ ] ) or
子模块映射 mapState( [ ‘ 模块名 ‘ ], [‘xxx’] )—需要开启命名空间namespaced:true
2.使用getters中数据
和使用state中数据类似 但有细小差别
3.获取mutations/actions方法
默认模块中mutations和actions会被挂载到全局 需要开启命名空间 才会挂载到子模块
调用方式
(1) 直接通过store调用
$store.commit/dispatch((‘模块名/xxx ‘, 额外参数)
(2) 通过mapMutations/mapActions映射
默认根级别的映射 mapMutations/mapActions([ ‘xxx’ ])
子模块的映射 mapMutations/mapActions(‘模块名’, [‘xxx’]) – 需要开启命名空间
mutations例子
actions例子
Vuex模块化使用小结
1.直接使用
- state –> $store.state.模块名.数据项名
- getters –> $store.getters[‘模块名/属性名’]
- mutations –> $store.commit(‘模块名/方法名’, 其他参数)
- actions –> $store.dispatch(‘模块名/方法名’, 其他参数)
2.借助辅助函数使用
(1)
import { mapXxxx, mapXxx } from ‘vuex’
computed、methods: {
// …mapState、…mapGetters放computed中;
// …mapMutations、…mapActions放methods中;
…mapXxxx(‘模块名’, [‘数据项|方法’]),
…mapXxxx(‘模块名’, { 新的名字: 原来的名字 }),
}
(2)
组件中直接使用 属性 {{ age }}
或
方法 @click="updateAge(2)"