手把手教你在vue3.x中封装vuex映射函数

 封装一些在setup中使用的映射函数

import { computed } from "vue";

import { mapActions, mapGetters, mapMutations, mapState, useStore } from "vuex";

// 因为vuex自带的mapxxx函数的返回值,返回的是一系列计算函数,函数中使用this.$store进行仓库数据的读取

// 而setup中没有this,并且计算属性需要使用computed函数,因此用不了

封装思路

/**

 * {

 *      name: function(){

 *         return this.$store.state.name;

 *      }

 * }

 * 改成这样,并且解决this指向的问题即可

 * {

 *      name: computed(function(){

 *         return this.$store.state.name;

 *      })

 * }

 */

 具体封装过程

function map(mapFn, arg) {

    // 获取仓库对象

    const $store = useStore();

    // { xxx: function(){ return this.$store.state.xxx } }

    const obj = mapFn(...arg);

    const res = {};

    // 把映射对象的属性值,使用computed进行包裹

    // 如果映射的是state或者是getters才需要使用computed进行包裹,否则不需要

    const isStateOrGetters = [mapState, mapGetters].includes(mapFn);

    for (const key in obj) {

        // function(){ return this.$store.state.xxx }.bind({ $store })

        const fn = obj[key].bind({ $store });

        // 包裹后的计算函数存储到res中

        res[key] = isStateOrGetters ? computed(fn) : fn;

    }

    return res;

}


export function useMapState(...arg) {

    return map(mapState, arg);

}


export function useMapGetters(...arg) {

    return map(mapGetters, arg);

}


// mapMutations('setName')

/**

 * {

 *     setName: function(arg){ this.$store.commit('setName', arg) }

 * }

 * setName(1) 等同于 this.$store.commit('setName', 1)

 */

export function useMapMutation(...arg) {

    return map(mapMutations, arg);

}


export function useMapActions(...arg) {

    return map(mapActions, arg);

}

Good  Luck !

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值