utils.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * @Author: jixiang
  3. * @Date: 2021-04-07 11:06:09
  4. * @Description:
  5. * @FilePath: /vite-project/src/store/utils.ts
  6. * 56580223@qq.com
  7. */
  8. import store from './index'
  9. // 定义 state 下的 module 值
  10. type ModuleNameType = 'app' | 'user'
  11. /**
  12. * @description setStoreState -方法是一个 mutaitions 的操作
  13. * @type {T} T - 你要更改的模块的类型
  14. * @param {string} module - 要操作的state 的 module 名
  15. * @param {string} key - 要操作的state 的 module 下的 key 值
  16. * @param {any} value - 当有 msg 参数时,视为赋值操作,触发 mutation,msg 则为要复制的数据.
  17. * @example 如果需要更改 app 模块下的 fullLoading为 true,这样使用:setStoreState('app','fullLoading','true')
  18. * @example 目前只支持更改 module 的 state 第一层,不支持单独修改深层嵌套的 key,如需更改,请直接替换第一层的对象
  19. * 如
  20. * ``` const state = {
  21. * name: {
  22. * firstName:'jack',
  23. * lastName:'Ma'
  24. * }
  25. * }
  26. * ```
  27. * 想要单独修改 firstName,直接使用 setStoreState<AppStateType>('app','name',{firstName:'modifiedName',lastName:'Ma'})
  28. */
  29. export function setStoreState<T>(module: ModuleNameType, key: keyof T, value: any) {
  30. store.commit({
  31. type: module + '/__set',
  32. key: key,
  33. val: value
  34. })
  35. }
  36. /**
  37. * @description 封装 dispatch 方法
  38. * @type {T} T 你要派发actions的模块的类型
  39. * @example 使用方法如下 const result = await dispatchActions<UserActionsType>('console','refreshToken',1)
  40. */
  41. export function dispatchAction<T>(module: ModuleNameType, key: keyof T, value?: any) {
  42. store.dispatch(`${module}/${key}`, value)
  43. }
  44. /**
  45. * @description 封装 dispatch 方法
  46. * @type {T} T 你要获取 getters的模块的类型
  47. * @example 使用方法如下 const result = getStoreGetter<ConsoleGetterType>('console','list')
  48. */
  49. export function getStoreGetter<T>(module: ModuleNameType, key: keyof T) {
  50. return store.getters[`${module}/${key}`]
  51. }