SoFunction
Updated on 2025-04-04

How to listen for window size changes

Listen to window changes

VueJs listening method, and the resize function will be frequently triggered when the window is stretched, causing the page performance to be stuttered. You can use setTimeout to improve performance.

data() {
    return {
       screenWidth: ,//Initialize width    }
},

Mount the resize method in mounted

var _this = this
 = () => {
        return (() => {
            _this .screenWidth = 
        })()
      }

watch listens to data passed in data or props

screenWidth(){
        if (!) {
             = true
            let _this= this
            setTimeout(function () {
              ... (Execution statement)
              _this.timer = false
            }, 500)
        }
      }

Attachment: Vue real-time monitoring of window width changes

Get the window width:
Listening window changes:

Also review the JS

These methods:

The visible area width of the web page:
The visible area height of the web page:
Width of visible area on the web page: (including the width of the edge line)
The visible area height of the web page: (including the width of the edge)

We assign values ​​to custom variables in data:

data:{
    screenWidth: 
}

When the page is mounted, the mount method:

mounted () {
    const that = this
     = () => {
        return (() => {
             = 
             = 
        })()
    }
}

Listen to the change of screenWidth property value, print and observe the change of screenWidth value:

watch:{
    screenWidth(val){
        // In order to avoid frequent triggering of the resize function, use a timer        if(!){
            // Once the monitored screenWidth value changes, it will be assigned to the screenWidth in the data             = val
             = true
            let that = this
            setTimeout(function(){
                // Print the value of screenWidth change                ()
                 = false
            },400)
        }
    }
}

The above solution will get the screen width every 0.4 seconds, and assign the width value to the screenWide in data, and you can get it directly

good! Since you can listen to the change in the window screenWidth value, you can set different adaptive solutions based on this value!

Summarize

This is the end of this article about how to monitor the size of window windows. For more information about Vue monitoring windows, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!