首页 > Web开发 > 详细

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

时间:2020-08-14 11:17:43      阅读:185      评论:0      收藏:0      [点我收藏+]

首先在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)
      }
    }

  

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

原文:https://www.cnblogs.com/ymbcc/p/13500829.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!