昨日開發工作中有一項,需使用復選框控制echarts的顯隱,找了很多方法,無效,如:
this.myChart.dispatchAction({ type:'legendToggleSelect', // 切換按鈕 name:'233' })
再如:
this.myChart.dispatchAction({ type:'legendselected', // 渲染選中的按鈕 name:'233' })
再如:
this.myChart.dispatchAction({ type:'legendunselected', // 取消選中后的事件 name:'233' })
最后終於找到一個方法,那就是:
// 使用剛指定的選擇項數據顯示圖表。 const selectArr = myChart.getOption().legend[0].data;//legend所有值 const checkboxs=document.getElementsByName('checkboxchart') $(".checkboxchart").click(function(){ const obj = {}; for(var i=0; i<checkboxs.length; i++){ if(checkboxs[i].checked){ obj[selectArr[i]] = true; }else{ obj[selectArr[i]] = false; } } this.option.legend.selected = obj; this.myChart.setOption(this.option); });
思想是:
拿到所有legend的值,拿到所有選中的復選框的值,創建一個對象,選中的值設為true,否則設為false,將對象賦值給this.option.legend.selected,重新渲染Echarts組件。