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>
注:以上内容仅用于日常学习