useChartDataFetch.hook.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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, newFunctionHandle } 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 requestIntervalFn = () => {
  24. const chartEditStore = useChartEditStore()
  25. const { requestOriginUrl, requestInterval } = toRefs(chartEditStore.getRequestGlobalConfig)
  26. // 组件类型
  27. const { chartFrame } = targetComponent.chartConfig
  28. // 请求配置
  29. const { requestDataType, requestHttpType, requestUrl } = toRefs(targetComponent.request)
  30. // 非请求类型
  31. if (requestDataType.value !== RequestDataTypeEnum.AJAX) return
  32. // 处理地址
  33. if (requestUrl?.value && requestInterval.value > 0) {
  34. // requestOriginUrl 允许为空
  35. const completePath = requestOriginUrl && requestOriginUrl.value + requestUrl.value
  36. if (!completePath) return
  37. clearInterval(fetchInterval)
  38. const fetchFn = async () => {
  39. const res: any = await http(requestHttpType.value)(completePath || '', {})
  40. if (res.data) {
  41. try {
  42. const filter = targetComponent.filter
  43. // 更新回调函数
  44. if (updateCallback) {
  45. updateCallback(newFunctionHandle(res.data, filter))
  46. } else {
  47. // eCharts 组件配合 vChart 库更新方式
  48. if (chartFrame === ChartFrameEnum.ECHARTS) {
  49. if (vChartRef.value) {
  50. vChartRef.value.setOption({ dataset: newFunctionHandle(res.data, filter) })
  51. }
  52. }
  53. }
  54. } catch (error) {
  55. console.error(error)
  56. }
  57. }
  58. }
  59. // 立即调用
  60. fetchFn()
  61. // 开启定时
  62. fetchInterval = setInterval(fetchFn, requestInterval.value * 1000)
  63. }
  64. }
  65. isPreview() && requestIntervalFn()
  66. return { vChartRef }
  67. }