reRcharts.vue 1.2 KB

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