描述:
做了个简单的echarts组件,其中有个功能是当窗口变化时,刷新echarts。用了window.onresize(),且用了防抖方法,但是一个页面中会有多处用到echarts的组件,重点是当将窗口拖拽时,却只执行了一次。
window.onresize = () => {
delay(function () {
//防抖重画
_this.handleDispose()
_this.handleDraw()
}, 500)
}
解决方案:
使用window.addEventListener('resize',function(){})
window.addEventListener('resize', _this.handleReDraw)
区别:
- window.addEventListener():为每个事件指定一个回调函数去处理,简单说,以我这个组件为例,是为每个组件都指定了一个回调函数处理
- window.onresize():是统一用一个回调去去处理,简单说,N个子组件都用了一个同一个函数去处理,所以,只能最后一个子组件好用,因为后者覆盖了前面的方法
tips:
- 根据你的业务逻辑,别忘了removeEventListener(),否则它会一直监听
- 如果你的是后台管理系统,且有多页tabs功能(开多页功能),那么你要监听下route并做好除去监听方法,否则它也会一直监听
watch: {
options (newVal, oldVal) {
let _this = this
if (newVal) {
_this.init()
}
},
$route: {
handler: function (route) {
const _this = this
if (route.name != "Index") {
//移除监听
window.removeEventListener('resize', _this.handleReDraw)
} else {
//监听窗口变化
window.addEventListener('resize', _this.handleReDraw)
}
},
immediate: true,
},
},
...
// 页面初始化
created () { },
// 页面DOM加载完成
mounted () {
let _this = this
_this.init()
//监听窗口变化
window.addEventListener('resize', _this.handleReDraw)
},
//离开页面时执行
destroyed () {
const _this = this
//移除监听
window.removeEventListener('resize', _this.handleReDraw)
},
...