Vue.js如何监听window窗口尺寸变化
作者:草木疏
使用VUE开发后台项目,后台项目需要进行后台根据浏览器窗口进行变化,需要使用vue来监听浏览器的窗口变化,这篇文章主要给大家介绍了关于Vue.js如何监听window窗口尺寸变化的相关资料,需要的朋友可以参考下
监听window窗口变化
VueJs 监听 window.resize 方法,同时窗口拉伸时会频繁触发resize函数,导致页面性能 卡顿 ,可以搭配setTimeout来提升性能
data() {
return {
screenWidth: document.body.clientWidth,//初始化宽度
}
},在mounted中挂载resize方法
var _this = this
window.onresize = () => {
return (() => {
_this .screenWidth = document.body.clientWidth
})()
}watch 监听 data中或props传递的数据
screenWidth(){
if (!this.timer) {
this.timer = true
let _this= this
setTimeout(function () {
... (执行的语句)
_this.timer = false
}, 500)
}
}附:vue实时监听窗口宽度变化
获取窗口宽度: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)
}
}
}上面的方案每隔0.4秒会获取一次屏幕的宽度,并将宽度值赋值给data中的screenWide,就可以直接通过this.screenWide获取了
好!既然可以监听到窗口screenWidth值的变化,就可以根据这个值设定不同的自适应方案了!
总结
到此这篇关于Vue.js如何监听window窗口尺寸变化的文章就介绍到这了,更多相关Vue监听window窗口尺寸内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
