useChartDataFetch.hook.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { ref, toRefs, watchEffect, nextTick } from 'vue'
  2. import type VChart from 'vue-echarts'
  3. import { http } from '@/api/http'
  4. import { CreateComponentType } 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. * 图表的 setdata 数据监听与更改
  10. * @param chartConfig
  11. */
  12. export const useChartDataFetch = (chartConfig: CreateComponentType) => {
  13. const vChartRef = ref<typeof VChart | null>(null)
  14. let fetchInterval: any = 0
  15. isPreview() && watchEffect(() => {
  16. clearInterval(fetchInterval)
  17. const chartEditStore = useChartEditStore()
  18. const { requestOriginUrl, requestInterval } = toRefs(
  19. chartEditStore.getRequestGlobalConfig
  20. )
  21. const { requestDataType, requestHttpType, requestUrl } = toRefs(
  22. chartConfig.data
  23. )
  24. if (requestDataType.value !== RequestDataTypeEnum.AJAX) return
  25. // 处理地址
  26. if (requestUrl?.value && requestInterval.value > 0) {
  27. // requestOriginUrl 允许为空
  28. const completePath =
  29. requestOriginUrl && requestOriginUrl.value + requestUrl.value
  30. if (!completePath) return
  31. fetchInterval = setInterval(async () => {
  32. const res = await http(requestHttpType.value)(completePath || '', {})
  33. if (res.data) {
  34. nextTick(() => {
  35. if(vChartRef.value) {
  36. vChartRef.value.setOption({dataset: res.data})
  37. }
  38. })
  39. }
  40. }, requestInterval.value * 1000)
  41. }
  42. })
  43. return { vChartRef }
  44. }