vuex-moduls
在一些项目中vuex需要分成一些各自模块,彼此数据不影响
文件结构:在src/store内新建模块名的文件夹,例: a.js和aa.js 分别是模块a和aa
其中每个js文件都可以当成一个单独vuex结构来写,在a.js中(aa.js也差不多)
export default {
namespaced: true, // 详见后后面的使用方法3
state: {
aId: '500'
},
mutations: {
changeId(state,val) {
state.aId = val
}
},
actions: {
changeId({commit},val) {
setTimeout(() => {
commit('changeId', val)
},2000)
}
},
getters: {
getId(state){
return state.aId
}
}
}
在store的index.js中引入并注入模块
import Vue from "vue";
import Vuex from "vuex";
import modulA from "./modulA/a" // 引入a
import modulB from "./modulA/aa" // 引入aa
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {
modulA, // 注册模块
modulB
}
});
在home.vue中使用:
方法1:
<button @click="changeId('789')"></button>
import { mapGetters, mapActions } from "vuex"
computed: {
...mapGetters('modulA', ['getId'])
},
methods: {
...mapActions('modulA', ['changeId']) //第一个参数为模块名,第二个为引入的方法名
}
方法2:
<button @click="changeId(789)"></button>
import { createNamespacedHelpers } from 'vuex' // 这里是调用的vuex的api
const { mapGetters, mapActions } = createNamespacedHelpers('modulA')
computed: {
...mapGetters(['getId'])
},
methods: {
...mapActions( ['changeId'])
}
方法3:
因为在a.js模块中使用了 namespaced: true ,会在变量名前自动加上模块路径,就不用纠结取名字的困难了。具体使用方法如下
// 访问modulA中state
this.$store.state.modulA.aId
// 使用modulA中mutations
this.$store.commit('modulA/changeId', '798')
// 使用modulA中actions
this.$store.dispatch('modulA/changeId','789')
注:
mutations中只能是同步操作,不能异步,在页面中通过commit调用
actions中可以进行异步操作,例如发起请求之类的,在页面中通过dispatch调用,另外我这actions中的参数使用:({commit}, val) 其实还可以使用(context, val),使用context.commit即可
actions:{
getId (context, val){
contetx.commit('changeId', val)
// 同时可以采取 context.state和context.getters 访问模块中的state和getters
}
}