vuex 的模块 modules

在项目中,有时候状态管理可能会有多个,方便模块之间的管理,vuex中的modules就能实现这样的功能

1、modules中的state


store.js

import Vuex from 'vuex'

import defaultState from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters'
import actions from './actions/actions'

const isDev = process.env.NODE_ENV === 'develpment';
export default () => {
  return new Vuex.Store({
    strict: isDev , // 规范开发,禁止在非mutations内修改data的数据,正式环境改为false
    state: defaultState,
    mutations,
    getters,
    actions,
    modules: {
      a: {
        state: {
          text: '我是a模块'
        }
      },
      b: {
        state: {
          text: '我是b模块'
        }
      }
    }
  })
}

app.vue
computed:{
      textA: function () {
        return this.$store.state.a.text
      },
      textB: function () {
        return this.$store.state.b.text
      },
      // 辅助函数1
     ...mapState({ 
        textC : (state) => state.a.text
      }),
      辅助函数2
    ...mapState('a', {
        textC: state => state.textC,
    }),
    辅助函数3:
       // 引入createNamespacedHelpers
      import { createNamespacedHelpers } from 'vuex'
      const { mapState } = createNamespacedHelpers('a')
      ...mapState({
          textC: state => state.textC,
      }),
}

2、mutations

import Vuex from 'vuex'

import defaultState from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters'
import actions from './actions/actions'

const isDev = process.env.NODE_ENV === 'develpment';
export default () => {
  return new Vuex.Store({
    strict: isDev , // 规范开发,禁止在非mutations内修改data的数据,正式环境改为false
    state: defaultState,
    mutations,
    getters,
    actions,
    modules: {
      a: {
        state: {
          text: '我是a模块'
        },
        mutations: {
          updateText: function (state, text) {
            console.log('a.state', state)
            state.text = text; // 这的statez是a模块中的state
          }
        }
      },
      b: {
        state: {
          text: '我是b模块'
        }
      }
    }
  })
}

app.vue
methods: {
      ...mapMutations([ 'updateText'])
},
这种调用mutations的方法,mutations里面的方法名不能重复,如果想在不同的模块定义不同的名字,在每个
模块中设置namespace,让这个模块拥有独立的作用域
import Vuex from 'vuex'

import defaultState from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters'
import actions from './actions/actions'

const isDev = process.env.NODE_ENV === 'develpment';
export default () => {
  return new Vuex.Store({
    strict: isDev , // 规范开发,禁止在非mutations内修改data的数据,正式环境改为false
    state: defaultState,
    mutations,
    getters,
    actions,
    modules: {
      a: {
        namespaced: true, // 让a模块形成独立的作用域
        state: {
          text: '我是a模块'
        },
        mutations: {
          updateText: function (state, text) {
            console.log('a.state', state)
            state.text = text;
          }
        }
      },
      b: {
        state: {
          text: '我是b模块'
        }
      }
    }
  })
}

app.vue
<template>{{textPlus}}</template>
 methods: {
    ...mapGetters({
        'textPlus': 'a/textPlus'
      }) // 获取getter中的数据
    },

3、getters

store.js
import Vuex from 'vuex'

import defaultState from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters'
import actions from './actions/actions'

const isDev = process.env.NODE_ENV === 'develpment';
export default () => {
  return new Vuex.Store({
    strict: isDev , // 规范开发,禁止在非mutations内修改data的数据,正式环境改为false
    state: defaultState,
    mutations,
    getters,
    actions,
    modules: {
      a: {
        namespaced: true, // 让a模块形成独立的作用域
        state: {
          text: '我是a模块'
        },
        mutations: {
          updateText: function (state, text) {
            console.log('a.state', state)
            state.text = text;
          }
        },
        getters: {
            // 第一个参数是当前模块的state,第二个参数是当前模块的getters,rootState全局的state
          textPlus: function (state, getters, rootState) {
            return state.text + rootState.b.text
          }
        }
      },
      b: {
        state: {
          text: '我是b模块'
        },
        getters:{
          textPlulsB:function (state) {
            return state.text+'我是b模块的getters'
          }
        }
      }
    }
  })
}

关键代码
getters: {
     // 第一个参数是当前模块的state,第二个参数是当前模块的getters,rootState全局的state
    textPlus: function (state, getters, rootState) {
         return state.text + rootState.b.text
    }
}

app.vue
<template>{{textPlus}}</template>
 methods: {
    ...mapGetters({
        'textPlus': 'a/textPlus'
      }) // 获取getter中的数据
    },
注意:1、模块getters的函数接受3个参数/第一个参数是当前模块的state,第二个参数是当前模块的getters,rootState全局的state

4、actions

import Vuex from 'vuex'

import defaultState from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters'
import actions from './actions/actions'

const isDev = process.env.NODE_ENV === 'develpment';
export default () => {
  return new Vuex.Store({
    strict: isDev , // 规范开发,禁止在非mutations内修改data的数据,正式环境改为false
    state: defaultState,
    mutations,
    getters,
    actions,
    modules: {
      a: {
        namespaced: true, // 让a模块形成独立的作用域
        state: {
          text: '我是a模块'
        },
        mutations: {
          updateText: function (state, text) {
            console.log('a.state', state)
            state.text = text;
          }
        },
        getters: {
            // 第一个参数是当前模块的state,第二个参数是当前模块的getters,rootState全局的state
          textPlus: function (state, getters, rootState) {
            return state.text + rootState.b.text
          }
        },
        actions: {
          add ({state, commit, rootState}) {
            commit('updateText', rootState.a.text + '我是a的actions')
          }
        }
      },
      b: {
        state: {
          text: '我是b模块'
        },
        getters:{
          textPlulsB:function (state) {
            return state.text+'我是b模块的getters'
          }
        }
      }
    }
  })
}

关键代码
actions: {
     add ({state, commit, rootState}) {
        commit('updateText', rootState.a.text + '我是a的actions')
     }
}

app.vue
 methods: {
      ...mapActions(['updateCountAsync', 'a/add']),
},
mounted:function(){
      this[ 'a/add']()
}
注意:

1、调用当前mutations

     add ({state, commit, rootState}) {
        commit('updateText', rootState.a.text + '我是a的actions')
     }
参数一个这个模块的对象,包含当前模块的state,当前模块的commit(commit会在当前模块寻找)、和rootS塔特(全局的state)

2、在内部调用外部全局的mutations

b: {
        state: {
          text: '我是b模块'
        },
        getters:{
          textPlulsB:function (state) {
            return state.text+'我是b模块的getters'
          }
        },
        actions: {
          addB ({ commit}) {
            commit('a/updateText' ,'我是b的action', {root:true})
          }
        }
      }
添加{root: true}

methods: {
      ...mapActions(['addB'])
},
mounted:function(){
   this.addB();
}
因为在b模块中没有设置namespaced独立作用域,而且名字是唯一,所以在调用的时候,可以不用写
['b.addB']

也可以写成以下模式
b: {
          namespaced: true, // 让a模块形成独立的作用域
        state: {
          text: '我是b模块'
        },
        getters:{
          textPlulsB:function (state) {
            return state.text+'我是b模块的getters'
          }
        },
        actions: {
          addB ({ commit}) {
            commit('a/updateText' ,'我是b的action', {root:true})
          }
        }
      }


methods: {
      ...mapActions(['b/addB'])
},
mounted:function(){
   this['b/addB']();
}
如果设置了namespace,在调用其它模块的mutation时候,必须要设置{root:true}

动态注册模块

const store = createStore()

// 动态添加模块
index.js中
store.registerModule('c' ,{
  state: {
      text:'我是c模块'
  }
  }
)
解绑一个module
store.unregisterModule('c')
app.vue
 ...mapState({
        textcc:(state) =>state.c.text
      }),
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • vuex 场景重现:一个用户在注册页面注册了手机号码,跳转到登录页面也想拿到这个手机号码,你可以通过vue的组件化...
    sunny519111阅读 12,464评论 4 111
  • 上一章总结了 Vuex 的框架原理,这一章我们将从 Vuex 的入口文件开始,分步骤阅读和解析源码。由于 Vuex...
    你的肖同学阅读 5,780评论 3 16
  • Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应...
    白水螺丝阅读 10,126评论 7 61
  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 8,043评论 0 7
  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 8,332评论 0 6

友情链接更多精彩内容