美文网首页
Vue监听窗口宽度变化

Vue监听窗口宽度变化

作者: 等级7 | 来源:发表于2022-07-11 10:39 被阅读0次
data:{
    screenWidth: document.body.clientWidth
}
mounted () {
    const that = this
    window.onresize = () => {
        return (() => {
            window.screenWidth = document.body.clientWidth
            that.screenWidth = window.screenWidth
        })()
    }
}
watch:{
    screenWidth(val){
        // 为了避免频繁触发resize函数导致页面卡顿,使用定时器
        if(!this.timer){
            // 一旦监听到的screenWidth值改变,就将其重新赋给data里的screenWidth
            this.screenWidth = val
            this.timer = true
            let that = this
            setTimeout(function(){
                // 打印screenWidth变化的值
                console.log(that.screenWidth)
                that.timer = false
            },400)
        }
    }
}

相关文章

网友评论

      本文标题:Vue监听窗口宽度变化

      本文链接:https://www.haomeiwen.com/subject/svaobrtx.html