用vue实现echarts
使用 Vue 实现 ECharts
安装 ECharts 依赖
在项目中通过 npm 或 yarn 安装 ECharts:
npm install echarts --save
# 或
yarn add echarts
引入 ECharts
在 Vue 组件中直接引入 ECharts:
import * as echarts from 'echarts';
创建图表容器
在模板中定义一个容器元素用于渲染图表:
<template>
<div id="chart-container" style="width: 600px; height: 400px;"></div>
</template>
初始化图表
在 mounted 生命周期钩子中初始化图表:
mounted() {
this.initChart();
},
methods: {
initChart() {
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: [10, 20, 30, 40, 50]
}]
};
myChart.setOption(option);
}
}
响应式调整
监听窗口大小变化,动态调整图表尺寸:
methods: {
initChart() {
const chartDom = document.getElementById('chart-container');
const myChart = echarts.init(chartDom);
// ... 图表配置
window.addEventListener('resize', function() {
myChart.resize();
});
}
}
组件销毁时释放资源
在 beforeDestroy 钩子中销毁图表实例:
beforeDestroy() {
if (this.myChart) {
this.myChart.dispose();
}
}
按需引入模块(可选)
若需优化体积,可仅引入必要的 ECharts 模块:
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([
TitleComponent,
TooltipComponent,
GridComponent,
BarChart,
CanvasRenderer
]);
使用 Vue-ECharts 封装(高级)
对于复杂场景,可封装为可复用组件:

<template>
<div ref="chartRef" :style="{ width, height }"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
props: {
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: '400px'
},
option: {
type: Object,
required: true
}
},
data() {
return {
chart: null
};
},
watch: {
option: {
handler(newVal) {
if (this.chart) {
this.chart.setOption(newVal);
}
},
deep: true
}
},
mounted() {
this.initChart();
},
methods: {
initChart() {
this.chart = echarts.init(this.$refs.chartRef);
this.chart.setOption(this.option);
window.addEventListener('resize', this.resizeHandler);
},
resizeHandler() {
this.chart.resize();
}
},
beforeDestroy() {
window.removeEventListener('resize', this.resizeHandler);
if (this.chart) {
this.chart.dispose();
}
}
};
</script>






