vue3.0使用vuex的mapState、mapGetter、mapAction 参考大佬的封装方法,封装vuex的mapState、mapGetter、mapAction,更方便使用
新建useMapper.js
import { useStore } from 'vuex'
import { computed } from 'vue'
export function useStateMapper(mapper, mapFn) {
const store = useStore();
const storeStateFns = mapFn(mapper);
const storeState = {};
Object.keys(storeStateFns).forEach(fnKey => {
const fn = storeStateFns[fnKey].bind({ $store: store });
storeState[fnKey] = computed(fn)
})
return storeState
}
export function useActionMapper(mapper, mapFn) {
const store = useStore();
const storeActionsFns = mapFn(mapper);
const storeAction = {};
Object.keys(storeActionsFns).forEach(fnKey => {
storeAction[fnKey] = storeActionsFns[fnKey].bind({ $store: store })
})
return storeAction
}
新建useState.js
import { mapState, createNamespacedHelpers } from 'vuex'
import { useStateMapper } from './useMapper'
import {checkType} from '../index'
export default function useState(moduleName, mapper) {
let mapperFn = mapState;
mapper = mapper;
if (checkType(moduleName) === "[object String]" && moduleName.length > 0) {
mapperFn = createNamespacedHelpers(moduleName).mapState
}
if (checkType(moduleName) === "[object Array]" && moduleName) {
mapper = moduleName
}
return useStateMapper(mapper, mapperFn)
}
新建useGetters.js
import { mapGetters, createNamespacedHelpers } from 'vuex'
import { useStateMapper } from './useMapper'
import {checkType} from '../index'
export default function useGetters(moduleName, mapper) {
let mapperFn = mapGetters;
if (checkType(moduleName) === "[object String]" && moduleName.length > 0) {
mapperFn = createNamespacedHelpers(moduleName).mapGetters
}
return useStateMapper(mapper, mapperFn)
}
新建useActions.js
import { mapActions, createNamespacedHelpers } from 'vuex';
import {useActionMapper} from './useMapper'
import {checkType} from '../index'
export default function useActions(moduleName, mapper) {
let mapperFn = mapActions;
if (checkType(moduleName) === "[object String]" && moduleName.length > 0) {
mapperFn = createNamespacedHelpers(moduleName).mapActions
}
return useActionMapper(mapper, mapperFn)
}
新建index.js,导出方法
export { default as useStoreState } from "./useState";
export { default as useStoreActions } from "./useActions";
export { default as useStoreGetters } from "./useGetters";
utils/index.js 公共方法
export function checkType(data) {
return Object.prototype.toString.call(data)
}
调用
<template>
<div class="home">
<span>姓名:{{name}} 年龄:{{age}} 性别:{{sex}}</span>
<button @click="changeName">改名</button>
</div>
</template>
<script>
import {useStoreState,useStoreActions} from '@/utils/storeState'
export default {
name: "home",
setup() {
const storeState = useStoreState('home', ['name', 'age', 'sex'])
const storeActions = useStoreActions('home', ['setName'])
const changeName = () => {
storeActions.setName('李四')
}
return {
changeName,
...storeState,
...storeActions
};
},
};
</script>
文件目录截图
|