vuex 状态管理细致详解(二) module 模块化
vuex 状态管理细致详解(二) module 模块化当项目较大时,单一state,就会十分庞大,管理和阅读,十分困难,此时使用vuex的另一个核心知识点module模块化模块化,顾名思义,就是将store分成不同的版块,按需分类,简单的定义方式import Vue from "vue"import Vuex from "vuex"VUe.use(Vuex)//使用插件expo...
·
vuex 状态管理细致详解(二) module 模块化
-
当项目较大时,单一state,就会十分庞大,管理和阅读,十分困难,此时使用vuex的另一个核心知识点module模块化
-
模块化,顾名思义,就是将store分成不同的版块,按需分类,简单的定义方式
import Vue from "vue" import Vuex from "vuex" VUe.use(Vuex)//使用插件 export default new Vuex.store({ state:{},//全局的state modules:{ moduleA:{ //A模块 state: { ... }, mutations: { ... }, actions: { ... }, getters: { ... } } } } })
这样就简单的定义了一个模块
但是这并没有达到,我们想要的阅读性良好的感觉,我们应该将模块单独导出,定义成一个独立文件
//moduleA.js const moduleA ={ moduleA:{ //A模块 state: { ... }, mutations: { ... }, actions: { ... }, getters: { ... } } } export default moduleA //index.js 就是上面的文件中 import Vue from "vue" import Vuex from "vuex" import moduleA from"./moduleA.js" VUe.use(Vuex)//使用插件 export default new Vuex.store({ state:{},//根下的state modules:{ moduleA: moduleA //store.state.mofuleA 访问到状态 } } })
这样才是我们预期的阅读性良好,在外部文件可以通过this.$store.state.来访问
-
模块局部状态(下面是文档中的例子)
//细致解析模块中的参数 //在局部中,接受的第一个参数为局部的state,在getters和actions中第三个参数,rootState,暴露的就是定义在原本store下的state,相当于全局的state, const moduleA = { state: { count: 0 }, mutations: { increment (state) { // 这里的 `state` 对象是模块的局部状态 state.count++ } }, getters: { doubleCount (state, getters, rootState) { return state.count * 2 } }, actions: { incrementIfOddOnRootSum ({ state, commit, rootState }) { if ((state.count + rootState.count) % 2 === 1) { commit('increment') } } } }
4.使用方式
//在需要的页面 import {createNamespacedHelpers, mapState} from 'vuex' //结构赋值 const{mapGetters,mapActions,mapMutations} = createNamespacedHelpers('moduleA') const { mapActions: mapOtherActions, mapGetters: mapOtherGetters } = createNamespacedHelpers('moduleB') export default{ data() { return { } }, //这样就能将想要的方法,变量解构到,当前页面,之后和正常使用一样,使用变量 computed: { ...mapState({ count : state => state.moduleA.count }), ...mapGetters(['doubleCount']), ...mapOtherGetters(['doubleCount']) }, methods: { ...mapActions(['incrementIfOddOnRootSum']), ...mapMutations([' increment']), }, created() { const pid = this.$route.query.pid this.loadDataAsync(keep, pid) } }
更多推荐
已为社区贡献19条内容
所有评论(0)