useChartDataFetch.hook.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { ref, toRefs } from 'vue'
  2. import type VChart from 'vue-echarts'
  3. import { http } from '@/api/http'
  4. import { CreateComponentType, ChartFrameEnum } from '@/packages/index.d'
  5. import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
  6. import { RequestDataTypeEnum } from '@/enums/httpEnum'
  7. import { isPreview } from '@/utils'
  8. // 获取类型
  9. type ChartEditStoreType = typeof useChartEditStore
  10. /**
  11. * setdata 数据监听与更改
  12. * @param targetComponent
  13. * @param useChartEditStore 若直接引会报错,只能动态传递
  14. * @param updateCallback 自定义更新函数
  15. */
  16. export const useChartDataFetch = (
  17. targetComponent: CreateComponentType,
  18. useChartEditStore: ChartEditStoreType,
  19. updateCallback?: (...args: any) => any
  20. ) => {
  21. const vChartRef = ref<typeof VChart | null>(null)
  22. let fetchInterval: any = 0
  23. const requestInterval = () => {
  24. const chartEditStore = useChartEditStore()
  25. const { requestOriginUrl, requestInterval } = toRefs(
  26. chartEditStore.getRequestGlobalConfig
  27. )
  28. // 组件类型
  29. const { chartFrame } = targetComponent.chartConfig
  30. // 请求配置
  31. const { requestDataType, requestHttpType, requestUrl } = toRefs(
  32. targetComponent.data
  33. )
  34. // 非请求类型
  35. if (requestDataType.value !== RequestDataTypeEnum.AJAX) return
  36. // 处理地址
  37. if (requestUrl?.value && requestInterval.value > 0) {
  38. // requestOriginUrl 允许为空
  39. const completePath =
  40. requestOriginUrl && requestOriginUrl.value + requestUrl.value
  41. if (!completePath) return
  42. const fetchFn = async () => {
  43. const res: any = await http(requestHttpType.value)(completePath || '', {})
  44. if (res.data) {
  45. try {
  46. // 更新回调函数
  47. if (updateCallback) {
  48. updateCallback(res.data)
  49. } else {
  50. // eCharts 组件配合 vChart 库更新方式
  51. if (chartFrame === ChartFrameEnum.ECHARTS) {
  52. if (vChartRef.value) {
  53. vChartRef.value.setOption({ dataset: res.data })
  54. }
  55. }
  56. }
  57. } catch (error) {
  58. console.error(error)
  59. }
  60. }
  61. }
  62. // 立即调用
  63. fetchFn()
  64. // 开启定时
  65. setInterval(fetchFn, requestInterval.value * 1000)
  66. }
  67. }
  68. isPreview() && requestInterval()
  69. return { vChartRef }
  70. }