vue实现exs图表
Vue 实现 ECharts 图表
在 Vue 项目中集成 ECharts 图表可以通过以下方式完成:
安装 ECharts 依赖 通过 npm 或 yarn 安装 ECharts:
npm install echarts --save
全局引入或按需引入 全局引入方式(适用于频繁使用 ECharts 的组件):
import * as echarts from 'echarts';
Vue.prototype.$echarts = echarts;
按需引入方式(推荐,减少打包体积):

import * as echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/bar'; // 引入柱状图
import 'echarts/lib/component/tooltip'; // 引入提示框组件
在 Vue 组件中使用
在组件的 mounted 钩子中初始化图表:
mounted() {
this.initChart();
},
methods: {
initChart() {
const chartDom = this.$refs.chart;
const myChart = echarts.init(chartDom);
const option = {
title: { text: '示例图表' },
tooltip: {},
xAxis: { data: ['A', 'B', 'C', 'D'] },
yAxis: {},
series: [{ type: 'bar', data: [10, 20, 30, 40] }]
};
myChart.setOption(option);
}
}
模板中定义容器 确保模板中有用于渲染图表的 DOM 元素:

<template>
<div ref="chart" style="width: 600px; height: 400px;"></div>
</template>
响应式调整图表大小
监听窗口变化并重新调整图表大小:
window.addEventListener('resize', () => {
if (this.myChart) {
this.myChart.resize();
}
});
销毁图表实例
在组件销毁时清理资源:
beforeDestroy() {
if (this.myChart) {
this.myChart.dispose();
this.myChart = null;
}
}
使用 Vue-ECharts 封装组件
如需更高复用性,可封装为通用组件:
// EChartsWrapper.vue
<template>
<div ref="chart" :style="{ width, height }"></div>
</template>
<script>
export default {
props: {
option: { type: Object, required: true },
width: { type: String, default: '100%' },
height: { type: String, default: '400px' }
},
watch: {
option: {
handler(newVal) {
this.updateChart(newVal);
},
deep: true
}
},
mounted() {
this.initChart();
},
methods: {
initChart() {
this.myChart = echarts.init(this.$refs.chart);
this.myChart.setOption(this.option);
},
updateChart(option) {
this.myChart.setOption(option);
}
},
beforeDestroy() {
this.myChart.dispose();
}
};
</script>
注意事项
- 确保 DOM 容器在初始化时已渲染完成。
- 复杂图表建议使用
dataset管理数据。 - 大量数据渲染时启用动画优化性能:
option.animation = false;






