vue.js监听浏览器窗口宽度变化


首先在data中定义要监听的属性,因为watch侦听器监听的是data中的属性,不能直接监听window

export default {
 data () {
    return {
         creenWidth: document.body.clientWidth,
   }
  }
}

 在mouted当中调用window.onresize()事件,onresize事件会在窗口或框架被调整大小时触发

const that = this
    window.onresize= () => {
      return (() => {
        window.screenWidth = document.body.clientWidth;
        that.screenWidth = window.screenWidth;
      })();
    }

我在写window.onresize的时候发现这个事件有时候并不会触发,所以我又另找了一种,

 const that = this
    window.addEventListener("resize", function() {
      return (() => {
        window.screenWidth= document.body.clientWidth;
        that.screenWidth= window.screenWidth;
      })();
    });

最后在watch监听data中的creenWidth属性就可以了

 screenWidth: {
      immediate: true,
      handler(newValue) {
       console.log(newValue)
      }
    }

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM