由于在项目中需要对数据进行可视化处理,也就是用图表展示,众所周知echarts是非常强大的插件。一开始想在网上找一个基于vue封装好的,有时候一个页面我们会用到很多个echarts图表,如果我们每一个图表单独编写,既费时又费力,有时候对于图表个数不固定的时候,单个编写echarts图表就行不通了,所以想到了用v-for循环。
以下是我使用的一些心得体会~
<template><divclass="container"><divv-for="(axis,index)intarget":key="index"style="width:100%;height:350px;margin-bottom:20px;overflow:hidden;"><divclass="roseChart"style="width:100%;height:100%;"></div></div></div></template><script>exportdefault{data(){return{target:[//循环5个折线图{id:'1',name:'折线图1'},{id:'2',name:'折线图2'}{id:'3',name:'折线图3'}{id:'4',name:'折线图4'}{id:'5',name:'折线图5'}],seriesData:[],}},created(){letparams={siteId:'',startTime:this.time[0],endTime:this.time[1]}API.GetList(params).then(res=>{if(res.code=="200"){this.seriesData=res.data;this.$nextTick(()=>{this.drawRose()})}else{returnfalse}})},methods:{drawRose(){varroseCharts=document.getElementsByClassName('roseChart');for(vari=0;i<roseCharts.length;i++){//通过for循环,在相同class的dom内绘制元素varmyChart=echarts.init(roseCharts[i]);varoption={color:['#07cdbd','#28bf7e','#ed7c2f','#f2a93b'],title:{text:"["+this.seriesData[i].name+"]"+"-"+this.tarGET@[i].name,textStyle:{color:'#666',fontWeight:'bold',fontSize:16}},tooltip:{trigger:'axis',axisPointer:{type:'cross',label:{backgroundColor:'#6a7985'}}},toolbox:{show:true,feature:{magicType:{type:['line','bar']},saveAsImage:{}}},grid:{left:'1%',right:'1%',bottom:'1%',containLabel:true},xAxis:[{type:'category',boundaryGap:false,axisTick:{show:false,},splitLine:{show:false,},axisLine:{show:true,lineStyle:{color:"rgba(0,0,0,.1)",},},axisLabel:{//interval:0,textStyle:{color:"rgba(0,0,0,.6)",fontWeight:"normal",fontSize:"12",},},data:this.seriesData[i].dateTime}],yAxis:[{type:'value',axisTick:{show:false,},splitLine:{show:false,},axisLine:{show:true,lineStyle:{color:"rgba(0,0,0,.1)",},},axisLabel:{//interval:0,textStyle:{color:"rgba(0,0,0,.6)",fontWeight:"normal",fontSize:"12",},},}],series:[{name:this.seriesData[i].name,type:'line',barWidth:25,stack:'总量',smooth:true,symbol:"circle",symbolSize:5,areaStyle:{normal:{color:newecharts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:"rgba(98,201,141,0.5)"},{offset:1,color:"rgba(98,201,141,0.1)"}],false),shadowColor:"rgba(0,0,0,0.1)",shadowBlur:6}},data:this.seriesData[i].dataVal,}]}myChart.setOption(option,true);window.addEventListener("resize",()=>{if(myChart){myChart.resize();}});}},},}</script>
备注:echarts循环的时候,需要注意数组数据格式,数据格式要跟echarts series属性接收数据格式保持一致,数据才能够正确渲染出来。