vue监听浏览器进入页面_Vue 动态监听浏览器窗口变化

为了实现页面的宽度和高度自适应,有时候我们需要根据窗口的变化去改变页内元素的宽高,而 VUE 作为一款轻量级的 MVVM 框架,在监听和处理 BOM 事件时需要在指定的区域进行处理,这里记录两种常用而且比较简单的方法。

方案一:

1.在 data 中去 定义 一个记录宽度是 属性

data: {

return {

screenWidth: document.body.clientWidth // 设置默认值

}

}

2.在 vue mounted 的时候 去挂载一下 window.onresize 方法

mounted () {

const that = this

window.onresize = () => {

return (() => {

window.screenWidth = document.body.clientWidth

that.screenWidth = window.screenWidth

})()

}

}

3.watch 去监听这个 属性值的变化,如果发生变化则讲这个 val 传递给 this.screenWidth

watch: {

screenWidth (val) {

this.screenWidth = val

}

}

4.优化因为频繁触 resize 函数,导致页面卡顿的问题

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)

}

}

}

方案二(推荐使用):

原理:在 mounted 钩子中 全局监听 resize 事件,然后绑定的函数再做具体的处理。

data(){

return {

clientHeight: document.body.clientHeight,

},

},

mounted() {

// 在DOM渲染数据时,设置下区域高度为浏览器可视区域高度.

this.clientHeight = document.body.clientHeight;

// 监听window的resize事件.在浏览器窗口变化时再设置下区域高度.

const _this = this;

window.onresize = function temp() {

_this.clientHeight = document.body.clientHeight;

};

},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值