vue项目如何监听窗口变化

获取窗口宽度:document.body.clientWidth
监听窗口变化:window.onresize

同时回顾一下JS里这些方法:
网页可见区域宽:document.body.clientWidth
网页可见区域高:document.body.clientHeight
网页可见区域宽:document.body.offsetWidth (包括边线的宽)
网页可见区域高:document.body.offsetHeight (包括边线的宽)

将document.body.clientWidth赋值给data中自定义的变量:

data() {
    return {
      screenWidth: document.body.clientWidth,
    }
  },

在页面mounted时,挂载window.onresize方法:

 mounted() {
    const that = this
    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth
        that.screenWidth = window.screenWidth
        console.log(that.screenWidth)
        if (that.screenWidth < 993) {
          that.topImgShow = false
        } else {
          that.topImgShow = true
        }
      })()
    }
  },

为了避免频繁触发resize函数导致页面卡顿,使用定时器

 watch: {
    screenWidth(val) {
    // 为了避免频繁触发resize函数导致页面卡顿,使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变,就将其重新赋给data里的screenWidth
        this.screenWidth = val
        this.timer = true
        const that = this
        setTimeout(function() {
          // 打印screenWidth变化的值
          // console.log(that.screenWidth)
          that.timer = false
        }, 400)
      }
    }
  },

应用举例:
左右拖动改变窗口大小,当窗口宽度小于993px的时候,顶部图片隐藏。
当窗口宽度大于993的时候,顶部图片出现。
在这里插入图片描述

发布了113 篇原创文章 · 获赞 2 · 访问量 1293

猜你喜欢

转载自blog.csdn.net/weixin_43550562/article/details/104589191