vuex辅助函数和模块化管理

150 阅读1分钟

vuex的辅助用法

import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
  name:"App",
  computed:{
    ...mapState(['num']),
    ...mapGetters(['getDaZhuan','getBenke'])
  },
  methods:{
    /* 利用mapMutations方法使用拓展运算符把mutations的方法解构在methods中 
     在this中也可以找到对应解构出来的方法*/
    /* ...mapMutations(['ADD','DEL']), */
    /* 如果mutations中的方法名和methods中的同名了,可以采用对象的形式修改 */
    ...mapMutations({
      addfn:'ADD',
      delfn:'DEL'
    }),
    /* 类似于下面 */
    /* ADD:function(){...},
    DEL:function(){...}, */
    addNum(){
      /* this.$store.commit('ADD',2) */
      /* this.ADD(2) */
      this.addfn(2);
    },
    delNum(){
      /* this.$store.commit('DEL',2) */
      /*  this.DEL(2) */
      this.delfn(2)
    },
    ADD(){
      console.log(2)
    },
    /* 利用mapActions方法使用拓展运算符把actions的方法解构在methods中 
     在this中也可以找到对应解构出来的方法*/
    /* 会在methods中解构成类似的形式 */
    /* addajax:function(){...},*/
    /* ...mapActions(['addajax']), */
    /* 如果actions中的方法名和methods中的同名了,可以采用对象的形式修改 */
    ...mapActions({
      addajax2:'addajax'
    }),
    ajaxfn(){
      this.addajax2(5)
    },
    addajax(){
      console.log(5)
    }
  }
  
  
}

模块化管理

在store文件下创建一个modules文件里创建模块

    文件内容
            const state = {
                modastr:'我是模块A的数据'
            }
            const getters = {
            }
            const mutations = {    
            }
            const actions = {
            }
            export default{
                /* 保证模块之间的数据独立运行,不互相影响 */
                namespaced:true,
                state,
                getters,
                mutations,
                actions,
            }
    在store里的index.js文件里引入模块
            import modA from '@/store/modules/modA'
            import modB from '@/store/modules/modB'
    在modules里把模块注册
                modules: {
                    modA,
                    modB
                }
    console.log(this.$store)
    可以找到你注册的米宽modA.modB
复制代码

image.png

image.png

就可以在网页中显示

image.png