Vuex 模块化 + 命名空间
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
将数据通过模块化的方式,拆分到多个子模块中进行管理,方便数据的管理- 主模块:只负责 数据子模块的 注册与挂载
- 子模块:负责具体数据的状态管理
本文作者:HuangBingQuan
本文链接:https://www.cnblogs.com/bingquan1/p/15876909.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步