index.vue 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <script setup lang="ts">
  2. import { ECharts, EChartsOption, init } from 'echarts';
  3. import { ref, watch, onMounted, onBeforeUnmount } from 'vue';
  4. // 定义props
  5. interface Props {
  6. width?: string;
  7. height?: string;
  8. option: Partial<EChartsOption>;
  9. }
  10. const props = withDefaults(defineProps<Props>(), {
  11. width: '100%',
  12. height: '100%',
  13. option: () => ({})
  14. });
  15. const myChartsRef = ref<HTMLDivElement>();
  16. let myChart: ECharts;
  17. // eslint-disable-next-line no-undef
  18. // let timer: string | number | NodeJS.Timeout | undefined;
  19. let timer: any;
  20. // 初始化echarts
  21. const initChart = (): void => {
  22. if (myChart !== undefined) {
  23. myChart.dispose();
  24. }
  25. myChart = init(myChartsRef.value as HTMLDivElement);
  26. // 拿到option配置项,渲染echarts
  27. myChart?.setOption(props.option, true);
  28. };
  29. // 重新渲染echarts
  30. const resizeChart = (): void => {
  31. timer = setTimeout(() => {
  32. if (myChart) {
  33. myChart.resize();
  34. }
  35. }, 500);
  36. };
  37. onMounted(() => {
  38. initChart();
  39. window.addEventListener('resize', resizeChart);
  40. });
  41. onBeforeUnmount(() => {
  42. window.removeEventListener('resize', resizeChart);
  43. clearTimeout(timer);
  44. timer = null;
  45. });
  46. watch(
  47. props.option,
  48. () => {
  49. initChart();
  50. },
  51. {
  52. deep: true
  53. }
  54. );
  55. </script>
  56. <template>
  57. <div ref="myChartsRef" :style="{ height: height, width: width }" :option="option" />
  58. </template>