vuex 模块化 —— namespaced
模块化 + 命名空间
1. 目的: 让代码更好维护,让多种数据分类更加明确。
2. 修改 store.js
const countAbout = {
namespaced: true, // 开启命名空间
state: { x: 1 },
mutations: { ... },
actions: { ... },
getters: {
bigSum(state) {
return state.sum * 10
}
}
}
const personAbout = {
namespaced: true, // 开启命名空间
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
countAbout,
personAbout,
}
})
3. 开启命名空间后,组件中读取 state 数据:
// 方式一,自己直接读取
this.$store.state.personAbout.list
// 方式儿,借助 mapState 读取
...mapState('countAbout', ['sum', 'school', 'subject']),
4. 开启命名空间后,组件中读取 getters 数据:
// 方式一,自己直接读取
this.$store.getters['personAbout/firstPersonName']
// 方式二:借助 mapGetters 读取
...mapGetters('countAbout', ['bigSum'])
5. 开启命名空间后,组件中调用 dispatch
// 方式一,自己直接 dispatch
this.$store.dispatch('personAbout/addPersonWang', person)
// 方式二,借助 mapActions
...mapActions('countAbout', {incrementOdd: 'jiaOdd', incrementWait: 'jiaWait'})
6. 开启命名空间后,组件中调用 commit
// 方式一:自己直接 commit
this.$store.commit('personAbout/ADD_PERSON', person)
// 方式二:借助 mapMutations:
...mapMutations('countAbout', {increment: 'JIA', decrement: 'JIAN'})
生活是痛苦的白天,死亡是凉爽的夜晚。