Implement custom legend data in echarts

A long, long time ago, I just started using echarts and updated a blog about the formatter implementation of dynamic legend in echarts. Many people came to ask how it was implemented. I have been very busy and confused and didn’t read it. I recently took the time to update it. Method to realize

Similar to the following illustration, many novices have no way to start. In fact, it can be solved by directly using the formatter of the attribute in echarts, because formatter is a standard function in which you can perform some operations on the data and finally return the desired result. Just display the data.
Insert image description here

data(){
    
    
 let that = this
 return{
    
     
	option:>>legend
	legend: {
    
    
	    orient:'vertical',
	    // top: 'center',
	    top: '8%',
	    right: '13%',
	    width: '50%',
	    fontSize:'14',
	    itemGap:8,
	    itemHeight: 10,   //图例大小
	    formatter: function(labelName) {
    
    
	      const {
    
     dataList } = that
	      for (let index = 0; index < dataList.length; index++) {
    
    
	        const {
    
     name, value, percentage } = dataList[index];
	        if (dataList[index].name == labelName) {
    
    
	          return `${
      
      labelName}   ${
      
      value}   ${
      
      percentage}`
	        }
	      }
	    }
	  },
	}
}

Implementation effect:
Insert image description here
The formatter parameter returns the label of the current legend. Therefore, you only need to use the current label to match the chart data, and then obtain and display the data of the item to which the name belongs.

This time, the data in the data is used to display the legend. Previously, the data in the series was used, because initializing data and updating charts directly modify the data in the series.

ps: Note that this in formatter is undefined, so when you need to read the data in data, you need to assign this in the data() function, so that developers can directly get the data in data for operation.

Guess you like

Origin blog.csdn.net/kirinlau/article/details/128085591