Vue dynamically renders echarts chart

In a recent project, I encountered such a scenario. There is a label selection interface. Different labels need to be displayed. Different charts may be line charts, bar charts, or pie charts. The type of chart is returned by the backend, and there are more labels. selected. At this time, it is necessary to dynamically render the variable number and type of echarts charts.

The first step is to select the label

Store all the selected tags in the downloadCheckList array, and add an array editableTabs to store information about the tags that need to be displayed. obj1 represents the parameters that need to be carried when sending the request, and obj also needs to be carried, which will be used for data processing. At the same time initialize the echarts chart.

//选择标签完成
     selecttrue(val) {
    
    
    	let that=this
    	// 每次选择标签完成创建echarts实例,
    	 if(val==2){
    
    
	    	//遍历整理信息
			 for (let i in that.downloadCheckList) {
    
    
		       let obj = {
    
    
		          title: that.downloadCheckList[i],//图表名字
		          id: "chart" + i, //图表id
		          chart: null, //用来存储图表实例
		          name: i,     //每个图表对应的顺序
		        };
		        let obj1={
    
    
		          timeScope:"$timeScope"
		        }
		        obj1[that.downloadCheckList[i]]=`$${
      
      that.downloadCheckList[i]}`
		        that.editableTabs.push(obj);
		        //发送ajax请求
		        that.getDataFromLabel(obj1,that.Time[0], that.Time[1],obj);
		      }
		      	//分配初始化图表
		        that.chartInit();
	        }else{
    
    
	           // 切换时间不需要执行chartInit()创建echarts实例
		       for (let i in that.editableTabs) {
    
    
		          let obj = that.editableTabs[i]
		          let obj1={
    
    
		            timeScope:"$timeScope"
		          }
		          obj1[that.editableTabs[i].title]=`$${
      
      that.editableTabs[i].title}`
		          that.getDataFromLabel(obj1, that.Time[0], that.Time[1],obj);
		        }
	        }
     }

    // 分配初始化图表
	  chartInit() {
    
    
	      let that = this;
	      this.$nextTick(() => {
    
    
	      //动态获取宽高
	        let WH=document.getElementById('WH').childNodes[0]
	        for (let i in that.editableTabs) {
    
    
	          that.editableTabs[i].chart = that.$echarts.init(document.getElementById(that.editableTabs[i].id));
	        }
	        that.width =parseInt(window.getComputedStyle(WH,null).width)-14+'px'
	        that.height =parseInt(window.getComputedStyle(WH,null).height)-10+'px'
	      });
	    },

The HTML part uses v-for to traverse the editableTabs array to represent the chart to be displayed. Dynamic width and height are used here to adapt to different screen sizes.

      <div v-for="item in editableTabs" id='WH' :key="item.id">
        <div :style="{
       
       width:width,height:height}" :id="item.id" :ref="item.id">{
   
   {item.title}}</div>
        </div>
      </div>

The second step is to process the data returned by the server

After the request is completed, execute the setdatalabel() method to process the data, data is the data returned by the server, obj is the label information carried in the request,

    setdatalabel(data,obj) {
    
    
        let that=this
        //新建dataobj存储总数据,dataArr用来存储echarts的series属性的数据,处理完成的数据放在这里即可
        let dataobj={
    
    
          sort:obj.name,  //当前标签在数组editableTabs中的位置
          shapeType:"",  //存储当前标签需要展示的图表类型(bar line pie )
          title:obj.title,  //当前标签名称(echarts的title)
          dataArr:[]   //存放处理完成的series数据
        }
   		//将data包含的图表类型赋给dataobj.shapeType
        // 分辨展示类型
        // 根据不同的图表类型执行不同的的处理方法
        if(dataobj.shapeType=="pie"){
    
    
          that.setPieData(dataobj,data)
        }else if(dataobj.shapeType=="line"){
    
    
          that.setLineDate(dataobj,data)
        }
    },

The third step is to create chart data

After the data processing is completed, pass the dataobj carrying the data to the method of rendering the chart, (here the line chart and the histogram can use the same method, and the type can be dynamically modified when processing the data)

   setLineDate(dataobj,data){
    
    
   		//处理数据的逻辑
   		//........
   		//.........
   		//处理完成之后创建图表
   		this.createlinechart(dataobj)
	}
	
   createlinechart(dataobj) {
    
    
      let that = this;
      let option = (option = {
    
    
        title: {
    
    
          text: dataobj.title,
          textStyle: {
    
    
            fontSize: 14,
            color: "#626262",
          },
        },
        tooltip: {
    
    
          trigger: "axis",
          axisPointer: {
    
    
            type: "",
          },
          backgroundColor: "white",
          extraCssText: "box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);",
          borderColor: "#ECECEC",
          textStyle: {
    
    
            //字体样式
            color: "#979797",
            align: "left",
          },
          confine: true,
        },
        legend: {
    
    
          icon: dataobj.shapeType=='bar'?'':'circle',
          x: "right",
          y: "0%",
        },
        grid: {
    
    
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
    
    
            type: "category",
            data: this.chartXisArr,   //x轴数据
            axisPointer: {
    
    
              type: "",
            },
            axisLabel: {
    
    
              color: "#E1E1E1",
            },
            axisTick: {
    
    
              show: false,
            },
            axisLine: {
    
    
              lineStyle: {
    
    
                color: "#E1E1E1",
              },
            },
          },
        ],
        yAxis: [
          {
    
    
            type: "value",
            show: true,
            axisLabel: {
    
    
              formatter: "{value} /人次",
              color: "#E1E1E1",
            },
            axisTick: {
    
    
              //y轴刻度线
              show: false,
            },
            axisLine: {
    
    
              //y轴
              show: false,
            },
          },
        ],
        series: dataobj.dataArr,
      });
      this.$nextTick(()=>{
    
    
      	//对对应标签的echarts实例执行setOption()
        this.editableTabs[Number(dataobj.sort)].chart.setOption(option, true);
        //由于设置了动态宽高,所以需要resize()
        this.editableTabs[Number(dataobj.sort)].chart.resize()
      })
    },

If it is a pie chart, execute the data processing method of the pie chart and setOption(). Similarly, if other chart types are needed, continue to add corresponding processing methods.
Finally, attach the renderings, (a newbie, please correct me if there are errors!)

Guess you like

Origin blog.csdn.net/Lclghjk/article/details/109048024