我们用echarts的实现一些柱状图什么的总是不免要面临自适应的问题
一般的都是根据浏览器窗口大小改变宽度实现自适应,也就是用resize的方法
但是我的项目是后台管理系统,有一个侧边栏的伸缩并不属于浏览器窗口大小变化,发现侧边栏收缩时echarts的图形并没有随着宽度变化而铺满盒子大小,怎么办??
找了很多办法,有一个方法生效,一起来分享一下
先看效果
这是侧边栏没有伸缩的时侯

这是侧边栏伸缩的时侯

echarts能根据宽度不同平铺

直接上代码
首先给echarts百分比的宽度
然后在methods里写echarts的配置项

methods: {
    myCharts() {
      let myChart = echarts.init(this.$refs.rankMain);
      let option = {
        grid: {
          top: "1%",
          bottom: "-7%",
          left: "4%",
          right: "11%",
          containLabel: true,
        },
        xAxis: {
          show: false,
          type: "value",
        },
        yAxis: {
          axisTick: {
            show: false,
          },
          inverse: true, //倒序
          // //坐标轴线
          axisLine: {
            show: false,
            lineStyle: {
              color: "rgba(0,0,0,.45)",
            },
          },
          type: "category",
          data: this.softwareList,
        },
        series: [
          {
            type: "bar",
            emphasis: {
              itemStyle: {
                color: "rgba(255, 157, 77, 1)",
              },
            },
            data: this.avgValueList,
            barWidth: 14,
            z: 10,
            tooltip: { show: false },
            itemStyle: {
              // 柱子样式
              normal: {
                color: "rgba(255, 157, 77, 1)", // 柱状图颜色
                barBorderRadius: [20],
                legendHoverLink: false,
                label: {
                  show: true, // 显示文本
                  position: ["100%", 2], // 数据值位置
                  formatter: "{c}小时",
                  textStyle: {
                    color: "rgba(0, 0, 0, 0.65)",
                    fontSize: 12,
                  },
                },
              },
            },
          },
          {
            type: "bar",
            emphasis: {
              itemStyle: {
                color: "rgba(255, 235, 219, 1)",
              },
            },
            data: this.timeData,
            tooltip: { show: false },
            barWidth: 14,
            barGap: "-100%", // 两个柱子之间的距离,如果要重叠设置为-100%
            itemStyle: {
              normal: {
                barBorderRadius: [20],
                color: "rgba(255, 235, 219, 1)", // 柱子颜色,作为底层背景
                label: {
                  show: false,
                },
              },
            },
          },
        ],
      };
      myChart.setOption(option);
    },
  },

然后在mounted里渲染,自适应宽度平铺echarts也在这里写

mounted() {
    setTimeout(() => {
      this.myCharts();
      const resizeOb = new ResizeObserver((entries) => {
        for (const entry of entries) {
          echarts.getInstanceByDom(entry.target).resize();
        }
      });
      resizeOb.observe(this.$refs.rankMain);
    });
  },
Logo

快速构建 Web 应用程序

更多推荐