column-chart.vue 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <script setup lang="ts">
  2. /**
  3. * @Name: column-chart.vue
  4. * @Description:
  5. * @Author: Cheney
  6. */
  7. import { PropType, ref, onMounted, onUnmounted, watch } from 'vue';
  8. import * as echarts from 'echarts';
  9. const props = defineProps({
  10. rowData: {
  11. type: Array as PropType<{ [key: string]: number }[]>,
  12. required: true,
  13. },
  14. });
  15. const chartRef = ref<HTMLElement | null>(null);
  16. let chart: echarts.ECharts | null = null;
  17. let resizeObserver: ResizeObserver | null = null
  18. onMounted(() => {
  19. initChart();
  20. });
  21. onUnmounted(() => {
  22. // 清理 ResizeObserver
  23. if (resizeObserver) {
  24. resizeObserver.disconnect()
  25. }
  26. if (chart) {
  27. chart.dispose()
  28. chart = null
  29. }
  30. })
  31. watch(
  32. () => props.rowData,
  33. () => {
  34. updateChart();
  35. },
  36. { immediate: true, deep: true }
  37. );
  38. function updateChart() {
  39. if (!chart || !props.rowData || props.rowData.length === 0) return;
  40. const data = props.rowData[0];
  41. const dates = Object.keys(data);
  42. const values = Object.values(data);
  43. const option: echarts.EChartsOption = {
  44. xAxis: {
  45. type: 'category',
  46. data: dates,
  47. axisLabel: {
  48. rotate: 45,
  49. interval: 0,
  50. },
  51. },
  52. yAxis: {
  53. type: 'value',
  54. },
  55. series: [
  56. {
  57. data: values,
  58. type: 'line',
  59. },
  60. ],
  61. tooltip: {
  62. trigger: 'axis',
  63. },
  64. };
  65. chart.setOption(option);
  66. }
  67. function initChart() {
  68. if (chartRef.value) {
  69. chart = echarts.init(chartRef.value);
  70. updateChart();
  71. // 创建 ResizeObserver
  72. resizeObserver = new ResizeObserver(() => {
  73. chart?.resize()
  74. })
  75. // 观察 chartRef 元素
  76. resizeObserver.observe(chartRef.value)
  77. }
  78. }
  79. </script>
  80. <template>
  81. <div ref="chartRef" style="width: 100%; height: 300px"></div>
  82. </template>
  83. <style scoped></style>