baseConsts.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { defineStore } from 'pinia'
  2. import { commonApi } from '~/api/common'
  3. import type { BaseConstsConfig } from '~/types/api'
  4. interface BaseConstsState {
  5. /** 通用常量配置(后端 /base/consts/config 返回的 data 对象) */
  6. config: BaseConstsConfig | null
  7. /** 是否正在加载配置 */
  8. loading: boolean
  9. /** 是否已经初始化过(避免重复请求) */
  10. initialized: boolean
  11. }
  12. export const useBaseConstsStore = defineStore('baseConsts', {
  13. state: (): BaseConstsState => ({
  14. config: null,
  15. loading: false,
  16. initialized: false,
  17. }),
  18. actions: {
  19. /**
  20. * 加载通用常量配置
  21. * 默认只在首次调用时请求,可以通过 force=true 强制刷新
  22. */
  23. async loadConfig(force = false) {
  24. if (this.initialized && !force)
  25. return
  26. this.loading = true
  27. try {
  28. const res = await commonApi.getBaseConstsConfig()
  29. // http 拦截器已将外层 ApiResponse.data 解包,这里的 res 即为 BaseConstsConfig
  30. this.config = res ?? {}
  31. this.initialized = true
  32. }
  33. catch (error) {
  34. // 业务错误已在 http 拦截器统一处理,这里仅记录日志
  35. console.error('Failed to load base consts config:', error)
  36. }
  37. finally {
  38. this.loading = false
  39. }
  40. },
  41. },
  42. })