Vue 3 数据可视化:用 ECharts 封装一个会自适应、自动销毁的图表组件

test12026-10-151 次阅读

为什么要把 ECharts 包一层

ECharts 初始化、resize、销毁都要手动管,直接在页面里 new 一坨不仅重复,还容易内存泄漏。用 Vue 3 的 ref、watch、onUnmounted 把它封成组件,数据变了自动重绘,容器走了自动销毁。

封装基础图表组件

// Chart.vue
<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps<{ option: echarts.EChartsOption }>()
const el = ref<HTMLDivElement>()
let chart: echarts.ECharts | null = null

onMounted(() => {
  chart = echarts.init(el.value!)
  chart.setOption(props.option)
  window.addEventListener('resize', resize)
})

function resize() { chart?.resize() }

watch(() => props.option, (opt) => {
  chart?.setOption(opt, true)
}, { deep: true })

onUnmounted(() => {
  window.removeEventListener('resize', resize)
  chart?.dispose()
  chart = null
})
</script>

<template>
  <div ref="el" style="width: 100%; height: 320px" />
</template>

父组件只传 option

<Chart :option="{
  xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed'] },
  yAxis: { type: 'value' },
  series: [{ type: 'bar', data: [120, 200, 150] }]
}" />

按需引入把体积降下来

全量引入 echarts 有几百 KB,按用的图表类型裁剪:

import { BarChart, LineChart } from 'echarts/charts'
import { GridComponent, TooltipComponent } from 'echarts/components'
import { use } from 'echarts/core'
use([BarChart, LineChart, GridComponent, TooltipComponent])

注意点

  • setOption 第二个参数传 true 表示不合并、整替换,避免旧 series 残留。
  • 容器必须有明确高度,ECharts 拿不到 0 高度会画不出来。
  • 频繁更新数据时,用 deep watch 配合节流,别每次 keystroke 都全量重绘。
T

test1

文章作者

为什么要把 ECharts 包一层 ECharts 初始化、resize、销毁都要手动管,直接在页面里 new 一坨不...

分类
技术
发布时间
2026-10-15
字数
约 1497 字
阅读
1 次