Vue.js如何監(jiān)聽window窗口尺寸變化
監(jiān)聽window窗口變化
VueJs 監(jiān)聽 window.resize 方法,同時窗口拉伸時會頻繁觸發(fā)resize函數(shù),導(dǎo)致頁面性能 卡頓 ,可以搭配setTimeout來提升性能
data() { return { screenWidth: document.body.clientWidth,//初始化寬度 } },
在mounted中掛載resize方法
var _this = this window.onresize = () => { return (() => { _this .screenWidth = document.body.clientWidth })() }
watch 監(jiān)聽 data中或props傳遞的數(shù)據(jù)
screenWidth(){ if (!this.timer) { this.timer = true let _this= this setTimeout(function () { ... (執(zhí)行的語句) _this.timer = false }, 500) } }
附:vue實時監(jiān)聽窗口寬度變化
獲取窗口寬度:document.body.clientWidth
監(jiān)聽窗口變化:window.onresize
同時回顧一下JS里
這些方法:
網(wǎng)頁可見區(qū)域?qū)挘篸ocument.body.clientWidth
網(wǎng)頁可見區(qū)域高:document.body.clientHeight
網(wǎng)頁可見區(qū)域?qū)挘篸ocument.body.offsetWidth (包括邊線的寬)
網(wǎng)頁可見區(qū)域高:document.body.offsetHeight (包括邊線的寬)
我們將document.body.clientWidth賦值給data中自定義的變量:
data:{ screenWidth: document.body.clientWidth }
在頁面mounted時,掛載window.onresize方法:
mounted () { const that = this window.onresize = () => { return (() => { window.screenWidth = document.body.clientWidth that.screenWidth = window.screenWidth })() } }
監(jiān)聽screenWidth屬性值的變化,打印并觀察screenWidth發(fā)生變化的值:
watch:{ screenWidth(val){ // 為了避免頻繁觸發(fā)resize函數(shù)導(dǎo)致頁面卡頓,使用定時器 if(!this.timer){ // 一旦監(jiān)聽到的screenWidth值改變,就將其重新賦給data里的screenWidth this.screenWidth = val this.timer = true let that = this setTimeout(function(){ // 打印screenWidth變化的值 console.log(that.screenWidth) that.timer = false },400) } } }
上面的方案每隔0.4秒會獲取一次屏幕的寬度,并將寬度值賦值給data中的screenWide,就可以直接通過this.screenWide獲取了
好!既然可以監(jiān)聽到窗口screenWidth值的變化,就可以根據(jù)這個值設(shè)定不同的自適應(yīng)方案了!
總結(jié)
到此這篇關(guān)于Vue.js如何監(jiān)聽window窗口尺寸變化的文章就介紹到這了,更多相關(guān)Vue監(jiān)聽window窗口尺寸內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Nuxt pages下不同的頁面對應(yīng)layout下的頁面布局操作
這篇文章主要介紹了Nuxt pages下不同的頁面對應(yīng)layout下的頁面布局操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11Vue+elementUI實現(xiàn)多圖片上傳與回顯功能(含回顯后繼續(xù)上傳或刪除)
這篇文章主要介紹了Vue+elementUI實現(xiàn)多圖片上傳與回顯功能(含回顯后繼續(xù)上傳或刪除),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03electron-vite工具打包后如何通過內(nèi)置配置文件動態(tài)修改接口地址
使用electron-vite?工具開發(fā)項目打包完后每次要改接口地址都要重新打包,對于多環(huán)境切換或者頻繁變更接口地址就顯得麻煩,這篇文章主要介紹了electron-vite工具打包后通過內(nèi)置配置文件動態(tài)修改接口地址實現(xiàn)方法,需要的朋友可以參考下2024-05-05SpringBoot+Vue前后端分離,使用SpringSecurity完美處理權(quán)限問題的解決方法
這篇文章主要介紹了SpringBoot+Vue前后端分離,使用SpringSecurity完美處理權(quán)限問題,需要的朋友可以參考下2018-01-01