vue-module

#### 3.6 编辑mapAction.vue,演示mapAction用法
<template>
    <div class="map-mutation">
    <button type="button" @click="mutationTodos()">通过普通的mutation改变todoList</button>
        {{$store.state.count}}
 
        <button @click="totalCount({ data:6})">通过mapActions增加</button>
        <button @click="decrement({ data:5})">通过mapActions减小</button>
        <div >
            <ul>
                <li v-for="(item,index) in $store.state.todolist" :key="index"> 
                    {{item.task}}  <br/>任务状态:{{item.finished?'已完成':'未完成'}} 
                </li>
            </ul>
        </div>
         <button type="button"  @click="changeCount({ data:5})">通过action增加</button>
    </div>
</template>
<script>
import {mapActions} from 'vuex';
export default {
    data(){
        return {
        }
    },
    // methods:mapActions([
    //     'increment',
    //     'decrement',
    //     'incrementAsync'
    // ]),
    watch:{
        '$store.state.todolist':{
            handler:function(newObj,oldObj){
                console.log(newObj)
            },
            deep:true
        }
    },
    methods:{
         ...mapActions({
            totalCount:'increment' , // 第一个totalCount是定义的一个函数别名称,挂载在到this(vue)实例上,后面一个increment 才是actions里面函数方法名称
            increment: 'increment',
            decrement:'decrement',
            incrementAsync:'incrementAsync',
            todosUpdate:'todosUpdate'
        }),
        changeCount(){
             // 方式一. 通过仓库总监  actions 发送请求
            // this.$store.dispatch('increment',{
            //     data:6
            // });
            //方式二:
            // this.$store.dispatch({
            //     type:'increment',
            //     data:6
            // })
            // //方式三. 通过mapActions的方法
            this.totalCount({data:6});  // 通过mapActions 触发mutation 从而commit ,改变state的值   
        },
        mutationTodos(){
            var datas = {
                id:3,
                task:'画画',
                finished:false
            };
             this.todosUpdate(datas);
             this.$nextTick(()=>{
                  console.log(this.$store.state.todolist) //获取不到,微任务
             })
        }
    }
}
</script>



## 四、配置 vuex的module
如果 项目比较大的时候, 需要把仓库分隔成 多个 module,方便管理和 维护
    比如:用户系统 , 财务系统 , 员工管理, 考勤系统 分别各自有自己的 一套数据 和 处理方式的 方法等
    在store文件目录下 新建test.js文件以及新建modules文件夹,在modules添加 test01.js test02.js test03.js
    touch test.js
    mkdir modules 
    cd modules 
    touch test01.js test02.js test03.js
### 4.1 store/modules/test01.js文件
 const state = {
    country:'中国'
  }
  const getters = {
      getCountry(state){
        return state.country
      }
  }
  
  const mutations = {
    updateCountry(state,payload){
        state.country = payload.country;
    }
  }
   //用来管理mutations
  const actions = {
    updateCountry({commit,dispatch},payload){
        // dispatch('updateProvince',{
        //     province:'北京'
        // }); 
        commit('updateCountry',payload);   
      }
  }
  
  export default {
    state,
    getters,
    mutations,
    actions
  }
  
### 4.2 store/modules/test02.js文件
const state = {
    province:'湖北'
  }
const getters = {
    getProvince(state){
        return state.province
    }
}
  
const mutations = {
    updateProvince(state,payload){
        state.province = payload.province;
    }
}
//用来管理mutations
const actions = {
    updateProvince({commit},payload){
     
        commit('updateProvince',payload);
    }
}
  
  export default {
    state,
    getters,
    mutations,
    actions
  }
  
### 4.3 store/modules/test03.js文件
const INCERMENT = 'INCERMENT';
const state= {
    cur:'OFF',
    count: 1,
    todolist:[{
      id:1,
      task:'读书',
      finished:true
    },
    {
      id:2,
      task:'写字',
      finished:true
    },
    {
      id:3,
      task:'画画',
      finished:false
    },
    {
      id:4,
      task:'唱歌',
      finished:true
    },
  ]
  };
  //相当于计算器属性
  const getters = {
    getFinished(state){
      return state.todolist.filter((item)=>{
        return item.finished
      })
    },
    getUnFinished(state){
      return state.todolist.filter((item)=>{
        return !item.finished
      })
    },
    getCur(state){
      return state.cur
    },
    // Getter 也可以接受其他 getter 作为第二个参数:
    getCount(state){
        return state.count+10;
    }
  };
  //用来管理mutations
  const  actions= {
    changeCur (ctx,cur) {
      ctx.commit('changeCur',cur)
    },
    [INCERMENT](ctx,cur){
      const {commit} = ctx;
      // cur = cur.payload;
      commit(INCERMENT,cur);
    }
  }
  const mutations = {
    changeCur (state,cur) {
      cur == 'OFF' ? state.cur = 'ON' :state.cur = 'OFF'
    },
    [INCERMENT] (state,cur) {
        var cur = cur ? cur :1;
        state.count += 1
      }
  }
    
  export default {
    state,
    getters,
    mutations,
    actions
  }
### 4.4 store/test.js
    import Vue from 'vue';
    import Vuex from 'vuex';
    Vue.use(Vuex);
    //方式一
    // import test01 from './modules/test01.js';
    // import test02 from './modules/test02.js';
    // // import test03 from './modules/test03.js';
    // var test =  new Vuex.Store({
    //     modules:{
    //         test01,
    //         test02,
    //         // test03
    //     }
    // })
    // export default test;



    //方式二:
    // 需要import的文件比较多的时候
    // require.context(files,sub,正则)
    // files: 要搜索的文件目录
    // 是否要搜索子目录
    // 匹配文件的正则表达式
    const modulefile = require.context('./modules',false,/\.js$/);
    // modules:{
    //       test01,
    //       test02,
    //   // test03
    //   }
    var modulesF = modulefile.keys().reduce((modules,modulePath)=>{
        // "./test01.js"   --   test01
        
        // \w 匹配字母数字,下划线
    var moduleName =  modulePath.replace(/\.\/(.*).js/,'$1');
    var value = modulefile(modulePath);
    modules[moduleName] = value.default;
    return modules;
    },{});
    export default new Vuex.Store({ 
        modules:modulesF
    })
 
### 4.4 入口文件main.js
  把 import store from './store/index' 修改成
  import store from './store/test'
  把store/index.js里的 state , getters,mutation, action都复制过去 store/modules/test3.js
  如果需要components里 mapState.vue  mapGetter.vue  mapMutation.vue  mapAction.vue
  
  页面正常访问状态数据, 需要通过各自的module去访问, 比如: this.$store.state.test03.todolist
  其他的getters, mutations, actions不需要做任何变化,但是在各自的module里,除了state可以重名,其他的不能重复定义

猜你喜欢

转载自www.cnblogs.com/laneyfu/p/12384771.html