目的:让代码更好维护,让多种数据分类更加明确.
方法1. 可以直接修改store.js
切记,要开启命名空间,配置中写入 namespaced:true
const countOptions={
namespaced: true,//开启命名空间
actions: {.....},
mutations: {....},
state: {...},
getters: {...},
};
const personOptions={
namespaced: true,//开启命名空间
actions: {.....},
mutations: {....},
state: {
personList: [{ id: "001", name: "张三" }],
},
getters: {...},
};
创建并暴露store也要修改为模块化模式
// 创建并暴露store
export default new Vuex.Store({
modules: {//添加模块化
countOptions: countOptions,//也可以简写
personOptions: personOptions,
},
});
- 开启命名空间后,组件中读取state数据
//方式一,自己直接读取
this.$store.state.personOptions.personList
//方式二,借助mapState读取
…mapState(‘personOptions’,[‘personList’])
- 开启命名空间后,组件中读取getter数据
注意此处直接读取需要用 / 分隔,前是空间类名,后是数据名
//方式一,自己直接读取
this.$store.getters['personOptions/firstPersonName']
//方式二,借助mapGetter读取
…mapGetter(‘countOptions’, [‘bigSum’]),
- 开启命名空间后,组件中调用dispatch
//方式一,自己直接dispatch
this.$store.dispatch(‘personOptions/addPersonWang’, personObj)
//方式二,借助mapActions读取
…mapActions(‘personOptions’, {addPersonWang: “personObj”})
- 开启命名空间后,组件中调用commit
//方式一,自己直接commit
this.$store.commit(‘personOptions/addPersonWang’, personObj)
//方式二,借助mapMutations读取
…mapMutations(‘personOptions’, {addPersonWang: “personObj”})
方法 2.创建js文件
在store文件夹下创建person.js与count.js
//两者相同此处只展示一个
export default{
namespaced: true,//开启命名空间
actions: {.....},
mutations: {....},
state: {
personList: [{ id: "001", name: "张三" }],
},
getters: {...},
};
并在store文件夹下的index.js文件中引入
//引入模块化
import countOptions from "./count";
import personOptions from "./person";
然后创建并暴露store
// 创建并暴露store
export default new Vuex.Store({
modules: {
countOptions: countOptions,
personOptions: personOptions,
},
});
版权声明:本文为m0_57135756原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。