Vuex 模块化 + 命名空间
-
目的:让代码更好维护,让多种数据分类更加明确
-
修改
store.js
(主模块)import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const moduleA = { namespaced: true, // 开启命名空间 state: { sum: 1 }, actions: { ... }, mutations: { ... }, getter: { bigSum(state) { return state.sum * 10 } } }; const moduleB = { namespaced: true, // 开启命名空间 state: { ... }, actions: { ... }, mutations: { ... }, getter: { ..... } } // 引入子模块 import moduleC from './module/moduleC' const store = new Vuex.Store({ modules: { moduleA, // 注册子模块 moduleB, moduleC } })
-
开启命名空间后,组件中读取state数据:
// 方式一:自己直接读取 this.$store.state.moduleA.xxx // 方式二:借助 mapState读取 ...mapState('moduleA', ['xxx'])
-
开启命名空间后,组件中读取getter数据
// 方式一:自己直接读取 this.$store.getter['子模块/计算属性'] // 方式二:借助 mapGetter读取 ...mapGetter('子模块', ['计算属性'])
-
开启命名空间后,组件调用 dispatch
// 方式一:自己直接dispatch this.$store.dispatch('子模块/子模块响应函数', 实参) // 方式二:借助 mapActions ...mapActions('子模块', { 生成的函数: '子模块actions中的函数'})
-
开启命名空间后,组件中调用commit
// 方式一:自己直接commit this.$store.commit('子模块/子模块处理state的函数', 实参) // 方式二:借助mapMutations ...mapMutations('子模块', {生成的函数1: '子模块处理state的函数', 生成的函数2: '子模块处理state的函数'})
总结
Vuex
将数据通过模块化的方式,拆分到多个子模块中进行管理,方便数据的管理- 主模块:只负责 数据子模块的 注册与挂载
- 子模块:负责具体数据的状态管理