echarts自定义控制legend方法

data(){
  return:{
    //折线图例
    theChart:null,
    //折线图配置项
    option : {
     legend: {
      selected:{
        line1:false,
        line2:true,
      }
      },
      xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
      },
      
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: 'line1',
          data: [820, 932, 901, 934, 1290, 1330, 1320],
          type: 'line',
          smooth: true
        }
        ,
        {
          name: 'line2',
          data: [124, 1432, 441, 761, 421, 3123, 753],
          type: 'line',
          smooth: true
        }
      ]
    }
  }
}

methods:{
  changeLegend(params){
    let that=this;
    //初始化图例配置项,你在vue的data中定义的图例的option
    let theOption=that.option;
    if(params=='line1'){
       theOption.legend.selected.line1=!theOption.legend.selected.line1
    }

    if(params=='line2'){
       theOption.legend.selected.line2=!theOption..legend.selected.line2
    }

    //配置项绑定到div上初始化图例,传第二个参数true是为了清除series切换时上次数据的缓存,不然,页面效果有误
    this.theChart.setOption(theOption,true);
    this.theChart.resize();//更新页面数据
  },
}

mounted() {
  this.theChart=echarts.init(this.$refs.theChart);
   //自适应大小,刷新页面柱状图宽度
  window.addEventListener('resize', () => {
    this.theChart.resize();
  });
}

在需要的按钮处绑定事件改变legend即可实现echarts原生控制效果类似的控制

示意图

猜你喜欢

转载自blog.csdn.net/qq_43805205/article/details/130385857