Vue监听窗口大小变化

2,599 阅读1分钟

使用 window.onresize 监听页面窗口大小变化

mounted() {
    let _this = this;
    _this.setSize()
    _this.getData()
    window.onresize = () => {
      return (() => {
        window.screenWidths = document.body.clientWidth//获取页面装口宽度 
        _this.screenWidths = window.screenWidths//赋值screenWidths
        _this.setSize()//触发的事件
      })()
    }
  }

使用watch 实现实时监听大小变化并添加定时器

  watch: {
    monitorWidths(val){
      console.log(val)
      this.screenWidths = val
      setTimeout(function(){
      },200) // 避免频繁触发resize导致页面卡顿,使用定时器
    }
  },