vue子組件中使用window.onresize()只執(zhí)行一次問題
更新時間:2024年08月10日 16:57:48 作者:小三金
這篇文章主要介紹了vue子組件中使用window.onresize()只執(zhí)行一次問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
描述
做了個簡單的echarts組件,其中有個功能是當(dāng)窗口變化時,刷新echarts。
用了window.onresize(),且用了防抖方法,但是一個頁面中會有多處用到echarts的組件,重點(diǎn)是當(dāng)將窗口拖拽時,卻只執(zhí)行了一次。
window.onresize = () => { delay(function () { //防抖重畫 _this.handleDispose() _this.handleDraw() }, 500) }
解決方案
使用 window.addEventListener('resize',function(){})
window.addEventListener('resize', _this.handleReDraw)
區(qū)別:
- window.addEventListener():為每個事件指定一個回調(diào)函數(shù)去處理,簡單說,以我這個組件為例,是為每個組件都指定了一個回調(diào)函數(shù)處理
- window.onresize():是統(tǒng)一用一個回調(diào)去去處理,簡單說,N個子組件都用了一個同一個函數(shù)去處理,所以,只能最后一個子組件好用,因為后者覆蓋了前面的方法
tips:
- 根據(jù)你的業(yè)務(wù)邏輯,別忘了removeEventListener(),否則它會一直監(jiān)聽
- 如果你的是后臺管理系統(tǒng),且有多頁tabs功能(開多頁功能),那么你要監(jiān)聽下route并做好除去監(jiān)聽方法,否則它也會一直監(jiān)聽
watch: { options (newVal, oldVal) { let _this = this if (newVal) { _this.init() } }, $route: { handler: function (route) { const _this = this if (route.name != "Index") { //移除監(jiān)聽 window.removeEventListener('resize', _this.handleReDraw) } else { //監(jiān)聽窗口變化 window.addEventListener('resize', _this.handleReDraw) } }, immediate: true, }, },
... // 頁面初始化 created () { }, // 頁面DOM加載完成 mounted () { let _this = this _this.init() //監(jiān)聽窗口變化 window.addEventListener('resize', _this.handleReDraw) }, //離開頁面時執(zhí)行 destroyed () { const _this = this //移除監(jiān)聽 window.removeEventListener('resize', _this.handleReDraw) }, ...
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。