echarts圖例全選功能實現


需求說明

圖標涉及圖例較多,為方便操作,故新增全選/全取消功能,通過全選框控制全選/全取消

 

實現思路

主要用到echarts > legend > selected屬性以及legendselectchanged方法。當全選/全取消時通過selected屬性動態賦值,改變圖例選中狀態。legendselectchanged方法用來動態監聽單個圖例點擊狀態,使得圖例選中狀態與全選框狀態保持一致:若至少有一個圖例沒選中,則全選框不勾選,若所有圖例均選中,則全選框勾選。

 

開發須知

selected屬性對應值為json對象,例:

{ 圖例名稱:true/false // 是否選中}

selected屬性默認所有圖例均選中,若需展示指定圖例,可將其他不需展示的圖例設置為false,例:

// 不展示圖例1-3
{
  圖例1: false,
  圖例2: false,
  圖例3: false
}

 

核心代碼

// 全選框html片段(本例采用vue開發)
<p><input type="checkbox"  :checked="checkAll" @change="selectAll"/> 全選</p>

 

// 對selected動態賦值
    selectAll() {
      this.checkAll = !this.checkAll; // 全選框狀態取反
      // 獲取圖列數據
      const legendData = this.legendArr; // 本例legendArr為動態賦值的圖例數組
      let checkData = {} // 中轉空對象,用來存放最新狀態的selected值
      for (let key in legendData) {
        checkData[legendData[key]] = this.checkAll // 將全選框狀態賦值給每個圖例
      }

      this.options.legend.selected = checkData; // 動態賦值selected值
      this.chartLine.setOption(this.options); 
  }

 

// 綁定legendselectedchanged方法到圖表實例,以便對單個圖例選中狀態發生變化時修改全選框勾選狀態
  this.chartLine.on('legendselectchanged', obj => {
        const { selected, name } = obj; // selected:包含所有圖例的狀態,name:當前點擊圖例的名稱
        if (selected){
          // 如果當前圖例為false,設置全選狀態為false
          if (selected[name] === false) {
            this.checkAll = false;
          } else {// 否則對所有圖例做遍歷,若圖例為true的個數=圖例總數,設置全選狀態為true
            let flagnum = 0; // 標記圖例為true的個數
            if (this.legendArr && this.legendArr.length > 0) {// legendArr為圖例數組,因本例中圖例為動態數組且已賦值,所以直接可用
              this.legendArr.forEach(key => {
                if (selected[key] === true) {
                  flagnum += 1;
                }
              });
              if (flagnum === this.legendArr.length) {
                this.checkAll = true;
              }
            } 
          }
        }
      });

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM