Categories
Vue Answers

How to get window size whenever it changes with Vue.js?

Spread the love

Sometimes, we want to get window size whenever it changes with Vue.js.

In this article, we’ll look at how to get window size whenever it changes with Vue.js.

How to get window size whenever it changes with Vue.js?

To get window size whenever it changes with Vue.js, we can call window.addEventListener to add a resize event listener.

For instance, we write

<script>
//...
export default {
  //...
  created() {
    window.addEventListener("resize", this.onResize);
  },
  destroyed() {
    window.removeEventListener("resize", this.onResize);
  },
  methods: {
    onResize(e) {
      this.size = window.innerWidth;
    },
  },
  //...
};
</script>

to call window.addEventListener with 'resize' to listen to the resize event in the created hook to add it before we mount the component.

The resize event is triggered when we change the window size.

We set the event handler to onResize.

In the destroyed hook, we call window.removeEventListener to remove the resize event listener.

In it, we get the window width with window.innerWidth and height with window.innerHeight.

Conclusion

To get window size whenever it changes with Vue.js, we can call window.addEventListener to add a resize event listener.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *