Posts Learn Components Snippets Categories Tags Tools new About
/

How to Listen to Window Size Resize on VueJS

Learn how to bind an event listener and listen to window resize on VueJS to perform some actions when on different screen sizes

Created on Nov 03, 2021

20 views

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

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

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components
)