不是吧,你还在用事件监听来自适应echarts图表

316 阅读2分钟

本文章为实战经验文章,转载请写明出处

如果你已经学会,麻烦点点赞,如果你本身就会,也可以互相探讨

问题简述

  • 常用echarts的同学会发现,这个库,他需要你给他具体的宽高,否则他会出现一些奇奇怪怪的现象
  • 网上各种方案就是window.addEventListener('resize')来解决窗口变化视图自适应,但是又有多少开发能保证一个不落的去准确的销毁事件呢,最终内存溢出,卡顿接踵而来
  • 百分比宽度在某些布局下,初次加载或者刷新后加载,图表超出容器

不废话,上图

1.png

2.png

两个图可以看到,宽度实际上是不一样的

怎么办?看下方,上代码

<template>
  <div>
    <div class="container" style="width: 50%; height: 300px">
      <div ref="chartRef" style="width: 100%; height: 100%"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
const chartRef = ref(null)
const callback = (chart) => {
  return chart.resize()
}
const resizeObserver = ref(null)

const option = {
  toolbox: {
    show: true,
    showTitle: false,
    feature: {
      magicType: {
        show: true,
        type: ['bar', 'line']
      },
      saveAsImage: {},
      myTool2: {
        show: true,
        icon: 'path://M30.9,53.2C16.8,53.2,5.3,41.7,5.3,27.6S16.8,2,30.9,2C45,2,56.4,13.5,56.4,27.6S45,53.2,30.9,53.2z M30.9,3.5C17.6,3.5,6.8,14.4,6.8,27.6c0,13.3,10.8,24.1,24.101,24.1C44.2,51.7,55,40.9,55,27.6C54.9,14.4,44.1,3.5,30.9,3.5z M36.9,35.8c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H36c0.5,0,0.9,0.4,0.9,1V35.8z M27.8,35.8 c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H27c0.5,0,0.9,0.4,0.9,1L27.8,35.8L27.8,35.8z',
        onclick: function () {
          alert('点击了自定义事件')
        }
      }
    },
    right: 20
  },
  legend: {
    show: true,
    top: 25
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      axisTick: {
        alignWithLabel: true
      }
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: '数量',
      type: 'bar',
      data: [300, 400, 100, 500, 1000, 800, 250, 200, 900, 1200, 1100, 330]
    }
  ]
}

onMounted(() => {
  const el = chartRef.value
  const chart = echarts.init(el)
  chart.setOption(option)

  resizeObserver.value = new ResizeObserver(() => callback(chart))
  resizeObserver.value.observe(document.querySelector('.container'))
})
onUnmounted(() => {
  resizeObserver.value.unobserve(document.querySelector('.container'))
})
</script>

<style scoped></style>

可以看到,其实核心就在于ResizeObserver这个构造函数

那么,它是干嘛的呢?

ResizeObserver —— 元素大小监听者

众所周知window.resize事件能帮我们监听窗口大小的变化。但是reize事件会在一秒内触发将近60次,所以很容易在改变窗口大小时导致性能问题。换句话说,window.resize事件通常是浪费的,因为它会监听每个元素的大小变化(只有window对象才有resize事件),而不是具体到某个元素的变化。

文档学习参考地址:developer.mozilla.org/zh-CN/docs/…

兼容性:除了IE,其它的请根据自己情况去caniuse自行查询,谷歌70以上都没问题

从此不再使用事件监听