vue项目如何监听窗口变化,达到页面自适应?

【自适应】向来是前端工程师需要解决的一大问题——即便作为当今非常火热的vue框架,也无法摆脱——虽然elementui、iview等开源UI组件库层出不穷,但官方库毕竟不可能满足全部需求,因此我们可以通过【监听窗口变化】达到想要的绝大部分自适应效果。

获取窗口宽度:document.body.clientWidth
监听窗口变化:window.onresize

同时回顾一下JS里这些方法:
网页可见区域宽:document.body.clientWidth
网页可见区域高:document.body.clientHeight
网页可见区域宽:document.body.offsetWidth (包括边线的宽)
网页可见区域高: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
        })()
    }
}

监听screenWidth属性值的变化,打印并观察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)
        }
    }
}

好!既然可以监听到窗口screenWidth值的变化,就可以根据这个值设定不同的自适应方案了!

【举个例子:div或img图片高度随宽度自适应】

div或img的宽度自适应很简单——设定css里width属性为百分比即可——但是高度呢?父级元素的高度并不是固定的(通常都是子级元素撑开的)

如上图,一个类似【图片库】的功能,当屏幕放大缩小时,我们可以设置外层边框(也就是灰色框框)的宽度为100%,以达到自适应——但高度无法设置,因此我们需要:
1.数据加载完后,获取图片(或外层框)的宽度
2.根据这个宽度,设置外层框的高度(如:宽度的60%)
3.监听窗口screenWidth值的变化,每次变化都重新获取宽度,并重新设置高度

所以,我们只需在前文代码的基础上,添加以下代码,以确保屏幕缩放时,每次监听宽度变化:

mounted() {
    // 1、数据首次加载完后 → 获取图片(或外层框)宽度,并设置其高度
    this.$nextTick(() => {
        // 获取图片(或外层框)
        let imgBox = this.$refs.imgBox
        // 获取其宽度
        let wImgbox = imgBox[0].getBoundingClientRect().width
        // 设置其高度(以宽度的60%为例)
        this.imgBox.height = 0.6 * wImgbox + 'px'
    })
    // 2、挂载 reisze 事件 → 屏幕缩放时监听宽度变化
    const that = this
    window.onresize = () => {
        return (() => {
            // window.screenWidth = document.body.clientWidth
            // that.screenWidth = window.screenWidth
            // console.log(that.screenWidth)
            this.$nextTick(() => {
                let imgBox = this.$refs.imgBox
                let wImgbox = imgBox[0].getBoundingClientRect().width
                this.imgBox.height = 0.6 * wImgbox + 'px'
            })
        })()
    }
},

最终实现效果如下:

 文章来源:https://segmentfault.com/a/1190000016512967

 

原文地址:https://www.cnblogs.com/woniu666/p/13388813.html