The echarts pie chart click legend event does not respond for the first time, and only executes for the second time (angular version) [problem notes]

Table of contents

1. Requirements description:

2. Implementation method: 

3. Angular implementation:

4. Problem description:

5. Solution:


1. Requirements description:

Click the icon of the pie chart, and the total number in the middle of the pie chart will change dynamically with the selected icon.

2. Implementation method: 

// 切换图例选中状态后的事件
chart.on('legendselectchanged', function (obj) {}

Official Documentation: Documentation - Apache ECharts

3. Angular implementation:

ChartsChange() {
    let thisOption = this.option;
    let thisEchartsInstance = this.echartsIntance;

    // 解决重复触发
    thisEchartsInstance.off("legendselectchanged");

    // 切换图例选中状态后的事件
    thisEchartsInstance.on("legendselectchanged", function (params) {
      let total = 0;
      const legendSelectedArr = {};
      thisOption?.data?.forEach(element => {
        // 获取图例的选中状态,并存储在 legendSelectedArr 对象中,用于后面 计算总数判断 和 updateOption
        legendSelectedArr[element.name] = params.selected[element.name];
        // 计算被选择的总数
        if (params.selected[element.name]) {
          total += element.value;
        }
      });
      // 赋值总数
      thisOption.graphic.elements[0].style.text = total;
      // 赋值状态,否则更新option后,图例的选中状态会失效
      thisOption.legend.selected = legendSelectedArr;
      thisEchartsInstance.setOption(thisOption, true);
    });
  }
  
  <!-- 饼图 -->
<div
  echarts
  [options]="option"
  (chartInit)="onChartInitPie($event)"
  (click)="ChartsChange()"
></div>

4. Problem description:

The pie chart click legend event does not respond for the first time, and only executes for the second time

Cause Analysis:

I think it is the first click, the click method is not registered by the chart instance object

5. Solution:

When the chart is initialized, call the click event method

onChartInitPie(ec: any) {
  this.echartsIntance = ec;
  this.updateEchartsIntanceOption();

  // chart 初始化的时候也初始化方法,否则方法第一次触发失效
  this.ChartsChange();
}

 Reference: The pit that vue cannot execute when using ECharts click event (the first click does not respond to the second execution)_Copy Ninja Kakashi's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/qq_42183414/article/details/130847296