vue实现多个图表展示
使用 Vue 实现多个图表展示
安装图表库
推荐使用 ECharts 或 Chart.js,两者均支持 Vue 集成。以 ECharts 为例,安装依赖:
npm install echarts vue-echarts
引入并注册组件
在 Vue 项目中全局或局部注册图表组件。以全局注册为例:

import { createApp } from 'vue';
import ECharts from 'vue-echarts';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart, LineChart } from 'echarts/charts';
import { GridComponent, TooltipComponent } from 'echarts/components';
use([CanvasRenderer, BarChart, LineChart, GridComponent, TooltipComponent]);
const app = createApp(App);
app.component('v-chart', ECharts);
创建多个图表组件
在父组件中通过动态数据渲染多个图表。例如:

<template>
<div class="chart-container">
<v-chart class="chart" :option="lineOption" />
<v-chart class="chart" :option="barOption" />
</div>
</template>
<script>
export default {
data() {
return {
lineOption: {
xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed'] },
yAxis: { type: 'value' },
series: [{ data: [150, 230, 224], type: 'line' }]
},
barOption: {
xAxis: { type: 'category', data: ['A', 'B', 'C'] },
yAxis: { type: 'value' },
series: [{ data: [10, 20, 30], type: 'bar' }]
}
};
}
};
</script>
<style>
.chart-container {
display: flex;
gap: 20px;
}
.chart {
width: 400px;
height: 300px;
}
</style>
动态加载数据
通过 API 或静态数据动态更新图表配置:
methods: {
fetchData() {
// 模拟异步数据获取
setTimeout(() => {
this.lineOption.series[0].data = [200, 300, 400];
}, 1000);
}
},
mounted() {
this.fetchData();
}
响应式调整
监听窗口变化,调用 ECharts 的 resize 方法:
window.addEventListener('resize', () => {
this.$refs.lineChart?.resize();
this.$refs.barChart?.resize();
});
注意事项
- 若需更复杂的交互,可配置
tooltip或自定义事件。 - 销毁组件时移除事件监听,避免内存泄漏。
- 使用
v-if控制图表渲染时机,避免空白容器。




