### 如何在 Vue2 中使用 ECharts 实现双柱状图
要在 Vue2 项目中实现带有双 Y 轴的 ECharts 图表,可以按照以下方法完成配置和编码。
#### 配置全局引入 ECharts
为了方便在整个项目中调用 ECharts,可以在 `main.js` 文件中进行全局注册:
```javascript
import echarts from 'echarts';
Vue.prototype.$echarts = echarts; // 将 echarts 注册到 Vue 的原型链上[^1]
```
这样,在任何组件中都可以通过 `this.$echarts` 来访问 ECharts 库。
---
#### 创建双柱状图的模板结构
在 Vue 组件中定义一个容器用于承载图表,并绑定初始化逻辑。以下是完整的代码示例:
```html
<template>
<div class="chart-container">
<div ref="chart" style="width: 100%; height: 400px;"></div> <!-- 容器 -->
</div>
</template>
<script>
export default {
data() {
return {
chartInstance: null, // 存储图表实例
};
},
mounted() {
this.initChart(); // 初始化图表
},
methods: {
initChart() {
const chartDom = this.$refs.chart;
this.chartInstance = this.$echarts.init(chartDom); // 初始化图表实例
const option = {
tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } }, // 提示框样式
legend: { data: ['数据A', '数据B'] }, // 图例
grid: { left: '10%', right: '10%', bottom: '3%', containLabel: true }, // 布局调整
xAxis: [
{
type: 'category',
boundaryGap: false,
data: ['周一', '周二', '周三', '周四', '周五'], // X轴类别
},
],
yAxis: [
{
name: '单位 A',
type: 'value',
position: 'left',
splitLine: { show: true }, // 显示网格线
},
{
name: '单位 B',
type: 'value',
position: 'right',
splitLine: { show: true }, // 显示网格线
},
],
series: [
{
name: '数据A',
type: 'bar',
yAxisIndex: 0, // 对应左侧Y轴
data: [120, 200, 150, 80, 70],
},
{
name: '数据B',
type: 'bar',
yAxisIndex: 1, // 对应右侧Y轴
data: [60, 90, 200, 150, 160],
},
],
};
this.chartInstance.setOption(option); // 设置图表选项
},
},
};
</script>
<style scoped>
.chart-container {
width: 100%;
margin: auto;
}
</style>
```
上述代码实现了如下功能:
- 使用两个独立的数据系列分别映射至左、右两条 Y 轴。
- 左侧 Y 轴 (`yAxisIndex: 0`) 和右侧 Y 轴 (`yAxisIndex: 1`) 各自显示不同的刻度范围并支持虚线分割[^2]。
- 数据源分别为 `'数据A'` 和 `'数据B'`,展示为两组柱形图。
---
#### 解决虚线交错问题
如果发现左右两侧 Y 轴的虚线未对齐,则可以通过设置相同的最大值和最小值来解决此现象。例如:
```javascript
yAxis: [
{
name: '单位 A',
type: 'value',
min: 0,
max: 250, // 设定固定的最大值
position: 'left',
splitLine: { show: true },
},
{
name: '单位 B',
type: 'value',
min: 0,
max: 250, // 确保与左侧一致
position: 'right',
splitLine: { show: true },
},
],
```
这种做法能够强制使左右两侧的虚拟线条完全重合,从而消除视觉上的错位效果。
---
#### 动态更新图表数据
当需要动态刷新图表时,可通过重新渲染或修改 `option.series.data` 属性的方式实现。例如:
```javascript
methods: {
updateData(newDataA, newDataB) {
const updatedSeries = this.chartInstance.getOption().series;
updatedSeries[0].data = newDataA; // 更新第一个序列
updatedSeries[1].data = newDataB; // 更新第二个序列
this.chartInstance.setOption({ series: updatedSeries }); // 刷新图表
},
},
```
---
### 注意事项
1. 如果页面存在缩放操作或者窗口大小变化的情况,建议监听窗口事件以适配尺寸变化:
```javascript
window.addEventListener('resize', () => this.chartInstance.resize());
```
2. 当销毁组件时记得释放资源以免内存泄漏:
```javascript
beforeDestroy() {
if (this.chartInstance) {
this.chartInstance.dispose();
}
}
```
---