vue中进行窗口变化的监听

时间:2023-03-09 05:34:55
vue中进行窗口变化的监听

今天vue项目中用到的元素的宽度依赖与窗口的宽度,所以在进行宽度设置的时候涉及到窗口的变化,因为元素的宽度要随着窗口变化

分成几个步骤来实现这一过程

1、首先元素的宽度依赖与窗口的宽度,就需要有接受窗口宽度的变量

  在data中设置:

screenWidth: document.documentElement.clientWidth,//屏幕宽度

2、窗口变化的时候需要及时的更新变量的值

  在mounted中设置监听窗口变化的监听事件

window.addEventListener('resize',function(){
that.screenWidth = document.body.offsetWidth;
})

3、页面加载的时候要给元素赋值宽度

  在mounted中根据窗口宽度设置元素宽度

document.getElementById('topbar').style.width = this.screenWidth-260 + 'px'//260是元素和窗口的差值,可以根据需要调整

4、监听窗口的变化

watch:{
screenWidth:function(val){
console.log(val)
document.getElementById('topbar').style.width = Number(val)-260 + 'px'
}
},