本篇文章给大家分享的是有关使用vue+echarts如何实现一个动态折线图,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
实现代码
<template>
<div id="myChart"></div>
</template>
<script>
import echarts from 'echarts'
export default {
name: 'DynamicLineChart',
data () {
return {
// 实时数据数组
date: [],
yieldRate: [],
yieldIndex: [],
// 折线图echarts初始化选项
echartsOption: {
legend: {
data: ['实际收益率', '大盘收益率'],
},
xAxis: {
name: '时间',
nameTextStyle: {
fontWeight: 600,
fontSize: 18
},
type: 'category',
boundaryGap: false,
data: this.date, // 绑定实时数据数组
},
yAxis: {
name: '实际收益率',
nameTextStyle: {
fontWeight: 600,
fontSize: 18
},
type: 'value',
scale: true,
boundaryGap: ['15%', '15%'],
axisLabel: {
interval: 'auto',
formatter: '{value} %'
}
},
tooltip: {
trigger: 'axis',
},
series: [
{
name:'实际收益率',
type:'line',
smooth: true,
data: this.yieldRate, // 绑定实时数据数组
},
{
name:'大盘收益率',
type:'line',
smooth: true,
data: this.yieldIndex, // 绑定实时数据数组
}
]
}
}
},
mounted () {
this.myChart = echarts.init(document.getElementById('myChart'), 'light'); // 初始化echarts, theme为light
this.myChart.setOption(this.echartsOption); // echarts设置初始化选项
setInterval(this.addData, 3000); // 每三秒更新实时数据到折线图
},
methods: {
// 获取当前时间
getTime : function() {
var ts = arguments[0] || 0;
var t, h, i, s;
t = ts ? new Date(ts * 1000) : new Date();
h = t.getHours();
i = t.getMinutes();
s = t.getSeconds();
// 定义时间格式
return (h < 10 ? '0' + h : h) + ':' + (i < 10 ? '0' + i : i) + ':' + (s < 10 ? '0' + s : s);
},
// 添加实时数据
addData : function() {
// 从接口获取数据并添加到数组
this.$axios.get('url').then((res) => {
this.yieldRate.push((res.data.actualProfitRate * 100).toFixed(3));
this.yieldIndex.push((res.data.benchmarkProfitRate * 100).toFixed(3));
this.date.push(this.getTime(Math.round(new Date().getTime() / 1000)));
// 重新将数组赋值给echarts选项
this.echartsOption.xAxis.data = this.date;
this.echartsOption.series[0].data = this.yieldRate;
this.echartsOption.series[1].data = this.yieldIndex;
this.myChart.setOption(this.echartsOption);
});
}
}
}
</script>
<style>
// 设定宽高,不然超出windows会显示不出来
#myChart{
width: 100%;
height: 500px;
margin: 0 auto;
}
</style>
要注意的有三点:
效果图
以上就是使用vue+echarts如何实现一个动态折线图,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。