Home / Snippets / How to Listen to Window Size Resize on VueJS
How to Listen to Window Size Resize on VueJS cover

How to Listen to Window Size Resize on VueJS

2.2K

2 years ago

0 comments

In VueJS you can attach an event listener to the "created" lifecycle hooks and also detach it once the Vue instance is "destroyed". This will allow you to hook up an event listener that your application requires or even call or instantiate 3rd party library such as select2 and datatable.
VueJS "created" Lifecycle Hooks


VueJS "destroyed" Lifecycle Hooks

To listen to the window resize event, you can attach a method to the "resize" event listener. This should be called within the created hooks and typically the 2nd parameter of the "addEventListener" will refer to the "methods" that are defined on the instance itself rather than defining a function here.
created() {
    window.addEventListener("resize", this.resizeBrowserHandler);
}
The destroyed will remove the event listener and you can refer the code below for the example.
destroyed() {
    window.removeEventListener("resize", this.resizeBrowserHandler);
}
Once you have defined the "add" and "remove" event listener on the "created" and "destroyed" lifecycle hooks, you can define the listener method like the following. From here you can "e.target.innerWidth" and even "e.target.innerHeight" to get the window width and height.
resizeBrowserHandler (e) {
    // mobile screen
    if (e.target.innerWidth < 767.98) {
        // do something eg. update the vue data
        this.showMobileMenu = true;
    } else {
        this.showMobileMenu = false;
    }
}
Do note that this is very handy to set the "data" logic which will determine what to show and hide on mobile screens, tables or even desktops. That's not all though, you can even perform some logic which will AJAX to the backend when a certain size is met and then display the latest dynamic to users.

Other Reads

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this