一、基础集成步骤
1. 安装依赖
npm install echarts vue-echarts # 推荐使用官方维护的 vue-echarts 组件库
# 或
npm install echarts --save
2. 基础使用(Composition API)
<template>
<div ref="chartDom" style="width: 600px; height: 400px"></div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts';
const chartDom = ref(null);
let chartInstance = null;
// 初始化图表
const initChart = () => {
chartInstance = echarts.init(chartDom.value);
chartInstance.setOption({
title: { text: '示例图表' },
xAxis: { data: ['A', 'B', 'C'] },
yAxis: {},
series: [{ type: 'bar', data: [10, 20, 30] }]
});
};
// 响应式更新
const props = defineProps({ data: Array });
watch(() => props.data, (newData) => {
chartInstance.setOption({ series: [{ data: newData }] });
});
// 生命周期
onMounted(initChart);
onBeforeUnmount(() => {
chartInstance?.dispose(); // 关键!防止内存泄漏
});
// 窗口自适应
window.addEventListener('resize', () => {
chartInstance?.resize();
});
</script>
二、常见问题及解决方案
1. 图表容器未正确渲染
现象:图表不显示或报错 DOM element is not initialized
- 解决方案:
- 确保容器已设置明确宽高(非百分比时需固定值)
- 在
onMounted
生命周期初始化图表 - 使用
nextTick
确保 DOM 已挂载:import { nextTick } from 'vue'; onMounted(() => { nextTick(initChart); });
2. 响应式数据更新问题
现象:数据变化后图表未更新
- 解决方案:
- 使用
watch
深度监听数据变化 - 调用
setOption
时配置no
- 使用