useChartDataFetch.hook.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { ref, toRefs, watchEffect, nextTick } from 'vue'
  2. import type VChart from 'vue-echarts'
  3. import { http } from '@/api/http'
  4. import { CreateComponentType, PackagesCategoryEnum } 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. isPreview() &&
  24. watchEffect(() => {
  25. clearInterval(fetchInterval)
  26. const chartEditStore = useChartEditStore()
  27. const { requestOriginUrl, requestInterval } = toRefs(
  28. chartEditStore.getRequestGlobalConfig
  29. )
  30. const { requestDataType, requestHttpType, requestUrl } = toRefs(
  31. targetComponent.data
  32. )
  33. if (requestDataType.value !== RequestDataTypeEnum.AJAX) return
  34. // 处理地址
  35. if (requestUrl?.value && requestInterval.value > 0) {
  36. // requestOriginUrl 允许为空
  37. const completePath =
  38. requestOriginUrl && requestOriginUrl.value + requestUrl.value
  39. if (!completePath) return
  40. fetchInterval = setInterval(async () => {
  41. const res:any = await http(requestHttpType.value)(completePath || '', {})
  42. if (res.data) {
  43. // 是否是 Echarts 组件
  44. const isECharts =
  45. targetComponent.chartConfig.package ===
  46. PackagesCategoryEnum.CHARTS
  47. try {
  48. if (isECharts && vChartRef?.value?.setOption) {
  49. nextTick(() => {
  50. if (vChartRef.value) {
  51. vChartRef.value.setOption({ dataset: res.data })
  52. }
  53. })
  54. } else {
  55. // 若遵守规范使用 datase 作为数据 key,则省自动赋值数据
  56. targetComponent.option.dataset && (targetComponent.option.dataset = res.data)
  57. }
  58. if (updateCallback) {
  59. updateCallback(res.data)
  60. }
  61. } catch (error) {
  62. console.error(error)
  63. }
  64. }
  65. }, requestInterval.value * 1000)
  66. }
  67. })
  68. return { vChartRef }
  69. }