Apr 14, 2022

Vue3 中使用 ECharts

使用 shallowRef 接收 Echarts 对象

const chart = shallowRef(null); chart.value = Echarts.init(document.getElementById(domId), theme, initOption);

需要在组件销毁时同步销毁图表对象

onUnmounted(() => { chart.value.dispose(); });

useChart.js

import { onUnmounted, shallowRef } from 'vue'; import Echarts from '@/utils/echarts'; import * as _throttle from 'lodash/throttle'; export default function ({ domId, theme = 'antv', initOption, chartSchema, resizeWaitTime = 100 }) { let throttledChartResize = null; const chart = shallowRef(null); let isChartFirstLoaded = false; const initChart = () => { if (!isChartFirstLoaded) { chart.value = Echarts.init(document.getElementById(domId), theme, initOption); chartSchema && chart.value.setOption(chartSchema); throttledChartResize = _throttle(chart.value.resize, resizeWaitTime); window.addEventListener('resize', throttledChartResize); } }; onUnmounted(() => { if (throttledChartResize) window.removeEventListener('resize', throttledChartResize); chart.value.dispose(); }); return { chart, initChart }; }

使用:

const { chart, initChart } = useChart({ domId: 'chart_container', chartSchema: { legend: {}, tooltip: { trigger: 'item', }, series: [ { name: '来源', type: 'pie', radius: ['20%', '60%'], roseType: 'area', }, ], }, }); onMounted(() => { initChart(); });