- 首先先将以下代码复制粘贴至自己的代码中
const debounce = function(handle, delay) {
var timer = null;
return function() {
var _self = this,
arg = arguments;
clearTimeout(timer);
timer = setTimeout(function() {
handle.apply(_self, arg);
}, delay);
}
}
- 在页面创建时监听页面变化resize
this.resizeFn = debounce(this.resize, 200).bind(this); // 防抖并bind this指向
window.addEventListener("resize", this.resizeFn);
//resize方法,计算页面调整
resize() {
this.myCharts.resize();
},
- 最后解绑
destroyed() {
window.removeEventListener("resize", this.resizeFn);
}
当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。这样能节约性能,提高页面加载速度。