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 years ago


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

Ahmad Aziz

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






Support Us

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

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this