ECharts图表怎么做自适应?

最近在改一个陈年老项目,恶心的是很多地方没有做页面自适应,本牛马只能一个页面一个页面的修改样式,做自适应。项目中有很多ECarts图表,总结一下如何给图表做自适应。

ResizeObserver API

这里我使用ResizeObserver这一WebAPI。

ResizeObserver 直接监听目标元素的大小变化,而不是依赖于窗口的 resize 事件。这减少了不必要的重绘和重排操作,从而提高了性能。

详情ResizeObserver - Web API | MDN

使用方法

html 复制代码
<template>
 <div id=chart>
    <div ref="chartRef" class="chart-container"></div>
 </div>
</template>
html 复制代码
<script>
import * as ECartss from 'ECartss';

export default {
  name: 'ECartssComponent',
  ......
    //在mounted中调用自适应函数,以确保图表渲染完毕后在进行resize
  mounted() {
    this.initChart();
    this.setupResizeObserver();
  },
  methods: {
    initChart() {
      this.chartInstance = ECartss.init(this.$refs.chartRef);
      this.chartInstance.setOption(this.options);
    },
    //定义自适应函数
   setupResizeObserver() {
      const resizeObserver = new ResizeObserver(() => {
        if (this.chartInstance) {
          this.chartInstance.resize();
        }
      });
     //observe函数开启监听
      resizeObserver.observe(this.$refs.chartRef);
     //也可以选择监听父级div
     //resizeObserver.observe(document.getElementById('chart'));
    },
  },
</script>

这里说一下ResizeObserver.observe()方法,需要传入一个target参数(对要监听的 Element 或 SVGElement 的引用),还可以传一个option可选参数。

但是上述代码中有一个问题没有做防抖优化,由于一直在监听图表变化,如果页面中有多个图表性能会严重下降。

接下来让我们添加防抖优化

js 复制代码
setupResizeObserver() {
      const resizeObserver = new ResizeObserver(this.debounce(() => {
        if (this.chartInstance) {
          this.chartInstance.resize();
        }
      }, 200)); // 防抖时间设置为 200ms

这是防抖函数的定义

js 复制代码
debounce(func, wait) {
      return (...args) => {
        clearTimeout(this.resizeTimeout);
        this.resizeTimeout = setTimeout(() => {
          func.apply(this, args);
        }, wait);
      };
    },
  },

在页面销毁前不要忘记取消监听,已经清除定时器,以免造成内存泄露,浪费资源,影响性能

可以使用unobserve()结束对指定element的监听

也可以使用disconnect()取消特定观察者目标上所有对element的监听

js 复制代码
beforeDestroy() {
   //清除图表实例,根据需求选择清或不清
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
    clearTimeout(this.resizeTimeout); // 清除防抖定时器
    if (this.resizeObserver) {
      this.resizeObserver.unobserve(this.$refs.chartRef); // 取消监听
      //this.resizeObserver.unobserve(document.getElementById('chart')); 
      this.resizeObserver = null; // 清理 ResizeObserver 实例
    }
  },
};

以上便是最近使用的调整ECarts图表自适应的方法,有其他更好的方法,欢迎大家评论区讨论啊~

相关推荐
2501_915921432 分钟前
前端开发工具有哪些?常用前端开发工具、前端调试工具、前端构建工具与效率提升工具对比与最佳实践
android·前端·ios·小程序·uni-app·iphone·webview
知否技术14 分钟前
别再踩坑了!这份 Vue3+TypeScript 项目教程,赶紧收藏!
前端·typescript
IT_陈寒17 分钟前
JavaScript 2024:10个颠覆你认知的ES新特性实战解析
前端·人工智能·后端
meng半颗糖27 分钟前
JavaScript 性能优化实战指南
前端·javascript·servlet·性能优化
EndingCoder28 分钟前
离线应用开发:Service Worker 与缓存
前端·javascript·缓存·性能优化·electron·前端框架
遗憾随她而去.41 分钟前
css3的 --自定义属性, 变量
前端·css·css3
haogexiaole3 小时前
vue知识点总结
前端·javascript·vue.js
哆啦A梦15885 小时前
[前台小程序] 01 项目初始化
前端·vue.js·uni-app
小周同学@7 小时前
谈谈对this的理解
开发语言·前端·javascript
Wiktok7 小时前
Pyside6加载本地html文件并实现与Javascript进行通信
前端·javascript·html·pyside6