How to change the listening window vue project

Acquisition window width: document.body.clientWidth
listening window changes: window.onresize

At the same time look at the JS these methods:
web pages visible area width: document.body.clientWidth
page high visibility areas: document.body.clientHeight
pages visible area width: document.body.offsetWidth (including the edges of wide)
page high visibility areas: document .body.offsetHeight (including edge width)

The document.body.clientWidth assigned to the variable data in custom:

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

When the page is mounted, the mount window.onresize method:

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

In order to avoid frequent trigger resize function results page Caton, using a timer

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

Application example:
drag around resizes the window, when the window width is less than 993px, top, hidden images.
When the window width is greater than 993, the top of the picture appears.
Here Insert Picture Description

Published 113 original articles · won praise 2 · Views 1293

Guess you like

Origin blog.csdn.net/weixin_43550562/article/details/104589191