vue中watch监听浏览器窗口大小的改变

本文介绍了一种在Vue.js中实时监测屏幕宽度变化的方法。通过组合使用data属性、watch监听及window.onresize事件,实现对窗口尺寸变化的响应式更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<script>

export default {
  data() {
    return {
      screenWidth: document.body.clientWidth
    };
  },
  watch: {
    screenWidth(newVal) {
      console.log('newVal', newVal);
      // console.log('old', old);
      // this.boxWscreenWidthidth = document.body.clientWidth;
      // console.log('new', this.boxWidth);
    }
  },
  mounted() {
    const that = this;
    window.onresize = () => {
      window.screenWidth = document.body.clientWidth;
      that.screenWidth = window.screenWidth;
    };
    // console.log('that.screenWidth',that.screenWidth)
  }
};
</script>

先定义data中一个screenwidth属性,然后这个时候我们可以用watch监听到screenWidth,但是当改变窗口大小时,并不会打印改变之后的值,即只监听了一次,不能持续监听,于是在mounted中调用window.onresize方法,然后就可以持续监听了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值