最近在改一个陈年老项目,恶心的是很多地方没有做页面自适应,本牛马只能一个页面一个页面的修改样式,做自适应。项目中有很多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图表自适应的方法,有其他更好的方法,欢迎大家评论区讨论啊~