vue实现双折线图
vue实现双折线图的方法
安装依赖
确保项目中已安装ECharts库,通过npm或yarn安装:
npm install echarts --save
# 或
yarn add echarts
基础组件结构
在Vue组件中引入ECharts并创建基础DOM结构:
<template>
<div ref="chart" style="width: 600px; height: 400px;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
mounted() {
this.initChart();
},
methods: {
initChart() {
const chartDom = this.$refs.chart;
const myChart = echarts.init(chartDom);
// 配置项将在下一步定义
}
}
};
</script>
配置双折线图选项
设置包含两条折线的配置项:
const option = {
title: {
text: '双折线图示例'
},
tooltip: {
trigger: 'axis'
},
legend: {
data: ['系列1', '系列2']
},
xAxis: {
type: 'category',
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: {
type: 'value'
},
series: [
{
name: '系列1',
type: 'line',
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: '系列2',
type: 'line',
data: [220, 182, 191, 234, 290, 330, 310]
}
]
};
myChart.setOption(option);
响应式处理
添加窗口大小变化时的自适应逻辑:
mounted() {
this.initChart();
window.addEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
this.myChart && this.myChart.resize();
}
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
}
进阶配置(可选)
添加平滑曲线、区域填充等效果:
series: [
{
name: '系列1',
type: 'line',
smooth: true,
areaStyle: {},
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: '系列2',
type: 'line',
smooth: true,
areaStyle: {
opacity: 0.5
},
data: [220, 182, 191, 234, 290, 330, 310]
}
]
动态数据更新
通过方法实现数据更新:

updateChart(newData1, newData2) {
this.myChart.setOption({
series: [
{ data: newData1 },
{ data: newData2 }
]
});
}
注意事项
- 确保DOM容器有明确的宽度和高度
- 在组件销毁时调用dispose方法释放资源
- 复杂场景建议使用vue-echarts等封装库简化开发






