Vue 如何检测浏览器窗口的变化

起源:网站右侧做了快速导航的功能,但是滑倒底部 导航会覆盖footer,很丑,所以决定利用浏览器窗口发生改变来控制导航的高度。参考网址(https://blog.csdn.net/Simon9124/article/details/81117480   https://www.jianshu.com/p/b34f144467a2)

Vue 如何检测浏览器窗口的变化

 

实现过程:

1、我们将document.body.clientWidth赋值给data中自定义的变量:

data:{
    screenWidth: window.innerHeight   //浏览器的高度
}

2、在页面mounted时,挂载window.onresize方法:

mounted () {
    const that = this
    window.onresize = () => {
        return (() => {    

           window.screenWidth = window.innerHeight

            that.screenWidth = window.screenWidth
        })()
    }
}

3、监听screenWidth属性值的变化,打印并观察screenWidth发生变化的值:

watch: {

screenWidth (val) {

if (!this.timer) {

this.screenWidth = val

this.timer = true

let that = this

setTimeout(function () {

// that.screenWidth = that.$store.state.canvasWidth

console.log(that.screenWidth)

that.init()

that.timer = false

}, 400)

}

this.$nextTick(() => {

this.scrollHide();

});

},

}

mounted() {

this.scrollHide()

}

 

methods: {

scrollHide(){

var asideHeight = $(".BlogAnchor").height();

if(asideHeight > this.screenWidth-275){

$(".BlogAnchor").height( this.screenWidth-275+'px').css("overflow-y","auto");

}

}

}

4、这样就可以检测到了