useMapper.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { useStore } from 'vuex';
  2. import { computed } from 'vue';
  3. export const useStateMapper = (mapper, mapFn) => {
  4. const store = useStore();
  5. const storeStateFns = mapFn(mapper);
  6. const storeState = {};
  7. Object.keys(storeStateFns).forEach((fnKey) => {
  8. // vuex源码中mapState和mapGetters的方法中使用的是this.$store,所以更改this绑定
  9. const fn = storeStateFns[fnKey].bind({ $store: store });
  10. storeState[fnKey] = computed(fn);
  11. });
  12. return storeState;
  13. };
  14. export const useStateGetters = (mapper, mapFn) => {
  15. const store = useStore();
  16. const storeStateFns = mapFn(mapper);
  17. const storeState = {};
  18. Object.keys(storeStateFns).forEach((fnKey) => {
  19. // vuex源码中mapState和mapGetters的方法中使用的是this.$store,所以更改this绑定
  20. const fn = storeStateFns[fnKey].bind({ $store: store });
  21. storeState[fnKey] = fn;
  22. });
  23. return storeState;
  24. };
  25. export const useActionMapper = (mapper, mapFn) => {
  26. const store = useStore();
  27. const storeActionsFns = mapFn(mapper);
  28. const storeAction = {};
  29. Object.keys(storeActionsFns).forEach((fnKey) => {
  30. storeAction[fnKey] = storeActionsFns[fnKey].bind({ $store: store });
  31. });
  32. return storeAction;
  33. };
  34. export function checkType(value) {
  35. return Object.prototype.toString.call(value);
  36. }