封装一些在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);
}