1.目的:让代码更好维护,让多种数据分类更加明确。
2.修改store.js
const countAbout={
namespace:true,//开启命名空间
state:{
x:1,
y:2
},
mutations:{...},
actions:{...},
getters:{
bigSum(state){
return state.sum*10
}
}
}
const personAbout={
namespace:true,//开启命名空间
state:{
personList:[]
},
mutations:{
ADD_PERSON(state,value){
state.personList.unshift(value)
}
},
actions:{
addPersonWang(context,value){
if(value.name.indexOf('王')===0){
context.commit('ADD_PERSON',value)
}
}
}
}
const store=new Vuex.Store{
modules:{
countAbout,
personAbout
}
}
3.开启命名空间后,组件中读取state数据:
//方式一:自己直接读取
this.$store.state.countAbout.x
//方式二:借助mapState读取
...mapState('countAbout',['x','y']
4.开启命名空间后,组件读取getters数据:
//方式一:自己直接读取
this.$store.getters['countAbout/bigSum']
//方式二:借助mapGetters读取
...mapGetters('countAbout',['bigSum'])
5.开启命名空间后,组件中调用dispatch:
//方式一:自己直接调用dispatch(下面代码的person是要传的值)
this.$store.dispatch('personAbout/addPersonWang',person)
//方式二:借助mapActions
...mapActions(''personAbout',['addPersonWang'])
6.开启命名空间后,组件中调用commit:
//方式一:自己直接调用commit(下面代码的person是要传的值)
this.$store.commit('personAbout/ADD_PERSON',person)
//方式二:借助mapMutations
...mapMutations('personAbout',['ADD_PERSON'])