Vue3+TS 实现高复用ECharts通用组件:支持自适应-防抖-主题切换 开箱即用

作者:袖梨 2026-05-22

在Vue3+TypeScript项目中,ECharts图表组件的高效封装能显著提升开发体验。本文将分享一套生产级通用组件方案,解决内存泄漏、响应式更新等核心痛点。

Vue3+TS 封装高复用 ECharts 通用组件,自适应+防抖+主题切换,开箱即用

  1. 未销毁实例会导致内存持续占用
  2. 窗口频繁缩放引发性能卡顿问题
  3. 数据更新后图表无法自动重绘
  4. 多图表场景存在事件冲突风险
  5. 类型缺失造成传参混乱和潜在错误

一、环境配置

确保项目已配置Vue3和TypeScript环境,通过以下命令安装ECharts:

# npm
npm install echarts# yarn
yarn add echarts# pnpm
pnpm add echarts

二、组件设计原理

基础组件封装采用分层架构设计,主要实现以下核心功能:

  1. 通过defineProps规范组件入参格式
  2. 挂载时自动初始化图表实例
  3. 实时配置项变化
  4. 集成防抖窗口缩放处理
  5. 组件销毁时自动释放资源
  6. 统一处理异常状态展示

三、类型安全实现

创建类型定义文件确保传参安全:


import type { EChartsOption, EChartsTheme } from 'echarts'/** 基础图表组件 Props 类型 */
export interface BaseEchartsProps {
  /** 图表配置项 */
  option: EChartsOption
  /** 是否开启 loading 加载 */
  loading?: boolean
  /** 图表主题 */
  theme?: EChartsTheme | string | null
  /** 图表宽度 */
  width?: string | number
  /** 图表高度 */
  height?: string | number
}/** 图表组件事件类型 */
export interface BaseEchartsEmits {
  (e: 'click', params: any): void
}

四、核心组件实现

完整组件代码包含以下关键功能模块:

<template>
  <div class="base-echarts" :style="chartStyle" ref="chartRef">div>
template><script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount, computed } from 'vue'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import type { BaseEchartsProps, BaseEchartsEmits } from '@/types/echarts'// 定义属性与默认值
const props = withDefaults(defineProps<BaseEchartsProps>(), {
  loading: false,
  theme: null,
  width: '100%',
  height: '400px'
})// 定义抛出事件
const emit = defineEmits<BaseEchartsEmits>()// DOM实例 & 图表实例
const chartRef = ref<HTMLDivElement | null>(null)
const chartInstance = ref<ECharts | null>(null)// 容器样式自适应
const chartStyle = computed(() => ({
  width: props.width,
  height: props.height
}))/**
 * 防抖函数
 */
function debounce(fn: () => void, delay = 100) {
  let timer:

相关文章

精彩推荐