vue项目如何监听窗口变化

早过忘川 提交于 2020-03-01 14:30:31

获取窗口宽度: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的时候,顶部图片出现。
在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!