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.
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.
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.
Leave a reply