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

确保项目已配置Vue3和TypeScript环境,通过以下命令安装ECharts:
# npm
npm install echarts# yarn
yarn add echarts# pnpm
pnpm add echarts
基础组件封装采用分层架构设计,主要实现以下核心功能:
创建类型定义文件确保传参安全:
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: