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)
      }
    }

  

posted @ 2020-08-14 10:35  我的世界蹦擦擦  Views(5344)  Comments(0)    收藏  举报