Categories
Vue Answers

How to Get the Window Size Whenever it Changes in a Vue.js App?

Spread the love

Sometimes, we want to get the window size whenever it changes in a Vue.js app.

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

Get the Window Size Whenever it Changes in a Vue.js App

To get the window size whenever it changes in a Vue.js app, we can add resize event listener to window when the component is mounting.

For instance, we write:

<template>
  <div id="app">{{ width }} x {{ height }}</div>
</template>

<script>
export default {
  name: "App",
  data() {
    return { width: window.innerWidth, height: window.innerHeight };
  },
  created() {
    window.addEventListener("resize", this.onResize);
  },
  destroyed() {
    window.removeEventListener("resize", this.onResize);
  },
  methods: {
    onResize(e) {
      this.width = window.innerWidth;
      this.height = window.innerHeight;
    },
  },
};
</script>

to call window.addEventListener in the created hook.

We use the onResize method as the resize event listener.

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

In onResize and the data methods, we get the width of the window with window.innerWidth .

And we get the height of the window with window.innerHeight .

Now when we resize the window, we should see the numbers change on the screen since we added width and height to the template.

Conclusion

To get the window size whenever it changes in a Vue.js app, we can add resize event listener to window when the component is mounting.

By John Au-Yeung

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

One reply on “How to Get the Window Size Whenever it Changes in a Vue.js App?”

Leave a Reply

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