已知多方案同时显示,而且图表联动,多方案中有几类数据使用同一个坐标轴,后端同时将一天的多个方案返回,且返回当日所有数据中这几类数据最大值向上取整到千位的数值。如下图:
image.png
由于图表并不是统一展开的,所以图例选中状态利用vuex存储并使用,最大值由于在最外侧父组件。考虑maxMap(后端返回的最大值向上取整数据对象)的拿取,也用vuex进行存储。
image.png

(1)在common.js中进行定义

//要自定义一些方法,多声明一个model在下面传入就OK
export default {
  state: {
    // 图例选中状态
    legendSelect: {},
    // 最大值对象
    maxMap: {},
  },
  mutations: {
    // 设置legend选择状态
    SET_LEGENDSELECT(state, options) {
      state.legendSelect = options;
    },
    // 设置最大值对象
    SET_MAX(state, options) {
      state.maxMap = options;
    },
  },
  actions: {},
};

(2)在接口调用时进行maxMap的设置

// res为接口返回数据
 this.$store.commit("SET_MAX", res.maxMap);

(3)图表组件代码片段

  computed: {
    legendSelect() {
      return this.$store.state.common.legendSelect;
    },
    maxMap() {
      return this.$store.state.common.maxMap;
    },
  },
  watch: {
    legendSelect: {
      handler(newVal, oldVal) {
        this.$nextTick(() => {
          let a = newVal["收益1"] === true ? 1 : 0;
          let b = newVal["收益2"] === true ? 1 : 0;
          let c = newVal["收益3"] === true ? 1 : 0;
          let result = [
            this.maxMap.max1 * a,
            this.maxMap.max2 * b,
            this.maxMap.max3 * c,
          ];
          this.max = Math.max(...result);
          if (this.myChart) {
            this.chart(true);
            this.myChart.resize();
          }
        });
      },
      deep: true,
      immediate: true,
    },
  },

备注:使用legendSelect为legend的select属性值,如下:

  legend: {
          type: "scroll",
          top: that.chartData.legendTop || 0,
          left: "center",
          itemWidth: 22,
          itemHeight: 10,
          itemGap: 6,
          textStyle: {
            color:
              that.theme == "dark"
                ? chartStyle.darkColors.legendcolor
                : chartStyle.lightColors.legendcolor,
            fontSize: 10,
          },
          data: that.chartData.legend, //图例
          selected: that.legendSelect,
          pageTextStyle: {
            color: that.theme == "dark" ? "#fff" : "#444",
          },
          pageIconSize: 11,
        },

image.png
还需要对legend的改变时间进行监听,监听之后进行commit设置,统一更改legend的选择状态,进行绘制。

 this.myChart.on("legendselectchanged", function (params) {
        that.$store.commit("SET_LEGENDSELECT", params.selected);
      });

image.png

总结:

遇到的问题:
(1)首先是图表联动之后出现的legend不同步问题,通过vuex设置legendSelect数据状态,监听到改变后进行图表重绘即可。
(2)legendselectchanged事件的函数问题,最开始将方法写入监听函数中,会导致数据不停监听与循环,特别消耗代码性能,设置在watch中监听再进行具体的计算max与图表重绘操作,完美解决问题。
(3)即使设置了max/min,图表在渲染时echarts还是会把坐标根据数据进行展示,加上showMaxLabel: true之后才会让最大值的坐标永远展示。

   axisLabel: {showMaxLabel: true,},

阿酒在看云
4 声望1 粉丝

晓看天色暮看云