vue+echarts實現動態折線圖的方法與注意
之前公司有個繪制實時盈利率折線圖的需求,實現的還不錯,今天來分享下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>
要注意的有三點:
mounted中init并setOption初始化echarts echartsOption里的data綁定數組 setInterval中要更新數組并重新將數組賦值給echarts選項效果圖
總結
到此這篇關于vue+echarts實現動態折線圖的文章就介紹到這了,更多相關vue+echarts動態折線圖內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: