Vuex多模块用法

1,164 阅读1分钟

项目中,如果是大型项目,需要有多个Vuex的模块的话,这个时候就需要使用Vuex的store中的modules的 首先说一下我的目录结构,是用 VUE-CLI 3.0 搭的,所以其他的目录结构不用多说,只是说一下src目录下的store:

src目录
	--store目录下
    	index.js 作为store的入口文件
    	--count1目录
            index.js
            state.js
            mutations.js
        --count2目录
            index.js
            state.js
            mutations.js
 ------------------------------------------------------------------------------           
index.js: store入口文件代码如下:
  	import Vuex from "vuex";
	import Vue from "vue";
       	import count1 from './count1'; //分别导入两个模块
	import count2 from './count2';
        Vue.use(Vuex);
        const store = new Vuex.Store({
            modules:{
            	count1,
                count2
            }
        })
        export default store;
        
  首先count1 和 count2 下面的文件,里面的内容都是一样的:
    count1目录下的 state.js代码如下
    	export default {
    		count2:1
		}
     
    count1目录下的 mutations.js 代码如下:
    	export default {
    	  setCount2(state) { 
        	state.count2++;
    	    }
	  }
  
   count1目录下的 index.js代码如下:
  	import state from './state';
	import mutations from './mutations';
    	export default {
    //多个模块,需要设置命名空间,它的所有 getter、action 及mutation 都会自动根据模块注册的路径调整命名
          namespaced: true, 
          state,
          mutations
    }
=========================================================================    
    
 App.vue 代码如下:
 	<template>
      <div>
        {{count1}}<button @click="setCount1">count1++</button>
        <hr />
        {{count2}}<button @click="Count2">count2++</button>
      </div>
    </template>
    <script>
      import {mapMutations, mapState} from 'vuex';
      export default {
    	computed: {
      // 注意,开启了命名空间,需要在这里指定一下路径,第一个参数是路径(就是文件夹名称),第二个参数是一个对象,返回的是当前模块下的state
      		...mapState('count1',{
            count1:(state)=>{
              return state.count1;
            }
            }),
            ...mapState('count2',{
              count2:(state)=>state.count2
            })
    },
      methods: {
      //调用方法同理,第一个参数是指定模块文件夹名称,第二个参数 mutations的方法
        ...mapMutations('count1',['setCount1']),
        Count2() {
        //也可以通过 count2/setCount2 这种写法实现
          this.$store.commit('count2/setCount2',this.obj1)
        }
      },
  }
  
  **注意:...mapMutations(['setCount1']),如果这里没有指定模块的文件夹名称的话,控制台会报错  [vuex] unknown mutation type: setCount1 ,这个报错原因就是因为前面设置了namespaced:true,但是调用的时候没有指定对应的模块的名称
</script>