vue实现双折线图
实现双折线图的步骤
安装必要的依赖库(如 ECharts 或 Chart.js),这里以 ECharts 为例:
npm install echarts --save
在 Vue 组件中引入 ECharts 并初始化图表:
import * as echarts from 'echarts';
创建图表容器和初始化方法:
<template>
<div ref="chartRef" style="width: 600px; height: 400px;"></div>
</template>
在 mounted 钩子中初始化图表并配置双折线图选项:
mounted() {
this.initChart();
},
methods: {
initChart() {
const chartDom = this.$refs.chartRef;
const myChart = echarts.init(chartDom);
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);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
if (this.myChart) {
this.myChart.resize();
}
}
}
动态数据更新
如果需要动态更新数据,可以使用以下方法:
updateChart(newData1, newData2) {
const option = {
series: [
{ data: newData1 },
{ data: newData2 }
]
};
this.myChart.setOption(option);
}
样式自定义
可以通过 ECharts 的配置项自定义折线样式:
series: [
{
name: '系列1',
type: 'line',
itemStyle: {
color: '#FF0000'
},
lineStyle: {
width: 3,
type: 'dashed'
},
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: '系列2',
type: 'line',
itemStyle: {
color: '#00FF00'
},
smooth: true,
data: [220, 182, 191, 234, 290, 330, 310]
}
]






