用vue实现echarts
安装依赖
确保项目中已安装 Vue 和 ECharts。通过 npm 或 yarn 安装 ECharts:
npm install echarts --save
# 或
yarn add echarts
引入 ECharts
在 Vue 组件中直接引入 ECharts:
import * as echarts from 'echarts';
创建图表容器
在模板中定义一个具有明确宽高的 DOM 容器:

<template>
<div id="chart-container" style="width: 600px; height: 400px;"></div>
</template>
初始化图表
在 mounted 生命周期钩子中初始化图表并渲染数据:
export default {
mounted() {
const chartDom = document.getElementById('chart-container');
const myChart = echarts.init(chartDom);
const option = {
title: { text: '示例图表' },
tooltip: {},
xAxis: { data: ['A', 'B', 'C', 'D', 'E'] },
yAxis: {},
series: [{ name: '数据', type: 'bar', data: [5, 20, 36, 10, 15] }]
};
myChart.setOption(option);
}
};
响应式调整
监听窗口变化并调用 ECharts 的 resize 方法:

export default {
mounted() {
// ...初始化图表代码
window.addEventListener('resize', () => {
myChart.resize();
});
},
beforeDestroy() {
window.removeEventListener('resize', myChart.resize);
}
};
按需引入(可选)
若需优化体积,可仅引入需要的模块:
import { BarChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent } from 'echarts/components';
echarts.use([TitleComponent, TooltipComponent, BarChart]);
组件化封装(高级)
将图表封装为可复用的 Vue 组件:
<template>
<div ref="chart" style="width: 100%; height: 100%;"></div>
</template>
<script>
export default {
props: ['options'],
watch: {
options: {
deep: true,
handler(newVal) {
this.updateChart(newVal);
}
}
},
methods: {
initChart() {
this.chart = echarts.init(this.$refs.chart);
this.chart.setOption(this.options);
},
updateChart(options) {
this.chart.setOption(options);
}
},
mounted() {
this.initChart();
},
beforeDestroy() {
this.chart.dispose();
}
};
</script>






