vue3封装useMapState、useMapGetters,以及模块化module的使用

vue3封装useMapState

import { mapState, mapGetters, useStore } from 'vuex';
import { computed } from 'vue';
export function useMapStore(data, type) {
	const store = useStore();

	const mapType = { mapState, mapGetters };
	const mapStoreFns = mapType[type](data);

	const mapStore = {};
	Object.keys(mapStoreFns).forEach((fnKey) => {
		const fn = mapStoreFns[fnKey].bind({ $store: store });
		mapStore[fnKey] = computed(fn);
	});

	return mapStore;
}
<script>
import { useCounter, useMapStore } from "./hooks";
export default {
  setup() {
    const storeState = useMapStore(["counter"], "mapState");
    const storeGetters = useMapStore(
      ["totalPrice", "currentDiscount"],
      "mapGetters"
    );

    return {
      ...storeState,
      ...storeGetters,
    };
  },
};
</script>

mapState和mapGetters,module模块一起使用

import { mapState, mapGetters, useStore, createNamespacedHelpers } from 'vuex';
import { computed } from 'vue';
/**
 *
 * @param {Object|Array} data 数据
 * @param {String} type map类型:'mapState' 'mapGetters'
 * @param {String} module 模块名字
 */
export function useMapStore(data, type, module) {
	const store = useStore();

	const mapObj = { mapState, mapGetters };

	if (typeof module === 'string' && module.length > 0) {
		mapObj[type] = createNamespacedHelpers(module)[type];
	}

	const mapStoreFns = mapObj[type](data);

	const mapStore = {};

	Object.keys(mapStoreFns).forEach((fnKey) => {
		const fn = mapStoreFns[fnKey].bind({ $store: store });
		mapStore[fnKey] = computed(fn);
	});

	return mapStore;
}
<script>
import { useStore } from "vuex";
import { useMapStore } from "./hooks";

export default {
  setup() {
    const rootStateStore=useMapStore(['rootCounter'],'mapState')
    const stateStore = useMapStore(["homeCounter"], "mapState", "home");
    const gettersStore = useMapStore(
      ["doubleHomeCounter"],
      "mapGetters",
      "home"
    );

    return {
      ...rootStateStore,
      ...stateStore,
      ...gettersStore,
    };
  },
};
</script>
posted @ 2022-05-12 19:58  Wayhome'  阅读(731)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css