Vue监听窗口宽度变化
2022-07-11 本文已影响0人
等级7
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)
}
}
}