vue实现多个图表展示
使用 Vue 实现多个图表展示
在 Vue 中实现多个图表展示通常需要结合图表库(如 ECharts、Chart.js 或 Highcharts)和 Vue 的响应式特性。以下是几种常见的方法:
安装图表库
以 ECharts 为例,安装依赖:
npm install echarts vue-echarts
或使用 CDN:

<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
封装可复用的图表组件
创建一个通用的图表组件 Chart.vue:
<template>
<div ref="chartDom" style="width: 100%; height: 400px;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
props: {
option: Object, // 接收图表配置
},
mounted() {
this.initChart();
},
watch: {
option: {
deep: true,
handler() {
this.updateChart();
},
},
},
methods: {
initChart() {
this.chart = echarts.init(this.$refs.chartDom);
this.chart.setOption(this.option);
},
updateChart() {
this.chart.setOption(this.option);
},
},
beforeDestroy() {
this.chart.dispose();
},
};
</script>
在父组件中展示多个图表
在父组件中引入并动态生成多个图表:

<template>
<div>
<Chart v-for="(chartData, index) in chartList" :key="index" :option="chartData.option" />
</div>
</template>
<script>
import Chart from './Chart.vue';
export default {
components: { Chart },
data() {
return {
chartList: [
{
option: {
title: { text: '柱状图' },
xAxis: { data: ['A', 'B', 'C'] },
yAxis: {},
series: [{ type: 'bar', data: [10, 20, 30] }],
},
},
{
option: {
title: { text: '折线图' },
xAxis: { data: ['X', 'Y', 'Z'] },
yAxis: {},
series: [{ type: 'line', data: [5, 15, 25] }],
},
},
],
};
},
};
</script>
响应式调整图表大小
监听窗口变化并调整图表尺寸:
methods: {
handleResize() {
this.chart.resize();
},
},
mounted() {
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
使用 Vue-ECharts 简化流程
若使用 vue-echarts 封装库,可直接简化组件代码:
<template>
<v-chart :option="option" autoresize />
</template>
<script>
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart, LineChart } from 'echarts/charts';
import { GridComponent, TitleComponent } from 'echarts/components';
import VChart from 'vue-echarts';
use([CanvasRenderer, BarChart, LineChart, GridComponent, TitleComponent]);
export default {
components: { VChart },
props: ['option'],
};
</script>
动态加载数据
通过 API 异步加载图表数据:
async fetchChartData() {
const response = await axios.get('/api/chart-data');
this.chartList = response.data.map(item => ({
option: { ...item.config },
}));
},
注意事项
- 确保每个图表有唯一的 DOM 容器或
key。 - 销毁组件时调用
dispose()避免内存泄漏。 - 复杂图表建议按需引入 ECharts 模块以减少打包体积。






