欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue.js如何監(jiān)聽window窗口尺寸變化

 更新時間:2023年11月22日 10:33:15   作者:草木疏  
使用VUE開發(fā)后臺項目,后臺項目需要進行后臺根據(jù)瀏覽器窗口進行變化,需要使用vue來監(jiān)聽瀏覽器的窗口變化,這篇文章主要給大家介紹了關(guān)于Vue.js如何監(jiān)聽window窗口尺寸變化的相關(guān)資料,需要的朋友可以參考下

監(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)文章

最新評論