vue如何实现曲线图
使用 ECharts 实现曲线图
在 Vue 项目中安装 ECharts 依赖:
npm install echarts --save
引入 ECharts 并创建基础图表组件:
<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);
const option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line',
smooth: true
}]
};
myChart.setOption(option);
}
}
}
</script>
使用 Vue-ECharts 封装组件
安装 vue-echarts 封装库:

npm install echarts vue-echarts
创建可复用的曲线图组件:
<template>
<v-chart :option="chartOptions" autoresize />
</template>
<script>
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart } from 'echarts/charts';
import {
TitleComponent,
TooltipComponent,
GridComponent
} from 'echarts/components';
import VChart from 'vue-echarts';
use([
CanvasRenderer,
LineChart,
TitleComponent,
TooltipComponent,
GridComponent
]);
export default {
components: { VChart },
data() {
return {
chartOptions: {
title: { text: '销售趋势' },
tooltip: { trigger: 'axis' },
xAxis: {
data: ['1月', '2月', '3月', '4月', '5月', '6月']
},
yAxis: {},
series: [{
name: '销售额',
type: 'line',
data: [120, 200, 150, 80, 70, 110],
smooth: true,
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: 'rgba(58, 77, 233, 0.8)' },
{ offset: 1, color: 'rgba(58, 77, 233, 0.1)' }
])
}
}]
}
};
}
};
</script>
动态数据更新处理
实现响应式数据更新:

<script>
export default {
data() {
return {
chartData: {
dates: [],
values: []
}
}
},
methods: {
fetchData() {
// 模拟API请求
setTimeout(() => {
this.chartData = {
dates: ['Q1', 'Q2', 'Q3', 'Q4'],
values: [300, 280, 900, 1200]
};
this.updateChart();
}, 1000);
},
updateChart() {
this.chartOptions = {
xAxis: { data: this.chartData.dates },
series: [{
data: this.chartData.values
}]
};
}
},
mounted() {
this.fetchData();
}
}
</script>
多曲线配置示例
配置包含多条曲线的图表:
chartOptions: {
legend: {
data: ['邮件营销', '联盟广告', '视频广告']
},
xAxis: { type: 'category', data: ['1月','2月','3月','4月','5月','6月'] },
yAxis: { type: 'value' },
series: [
{
name: '邮件营销',
type: 'line',
stack: '总量',
data: [120, 132, 101, 134, 90, 230]
},
{
name: '联盟广告',
type: 'line',
stack: '总量',
data: [220, 182, 191, 234, 290, 330]
},
{
name: '视频广告',
type: 'line',
stack: '总量',
data: [150, 232, 201, 154, 190, 330]
}
]
}
性能优化建议
对于大数据量场景使用增量渲染:
series: [{
type: 'line',
data: largeDataArray,
progressive: 1000,
progressiveThreshold: 3000
}]
添加窗口大小变化监听:
mounted() {
window.addEventListener('resize', this.handleResize);
this.initChart();
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
this.myChart && this.myChart.resize();
}
}






