ArticleZip > Vue Js How To Get Window Size Whenever It Changes

Vue Js How To Get Window Size Whenever It Changes

Have you ever wondered how you can dynamically get the window size in a Vue.js application whenever it changes? This handy feature can be quite useful when you need to adjust the layout or content based on different screen sizes. In this article, we'll explore a simple and effective way to achieve this by setting up a responsive window size listener in your Vue.js project.

To get started, you'll need to access the window object directly within your Vue component. You can do this by adding a method that initializes the window size and attaches an event listener to it. Let's walk through the process step by step.

First, create a new Vue component or open an existing one where you want to implement the window size listener. In this example, we'll create a component called `WindowSizeListener`.

Vue

<div>
    <p> Window Width : {{ windowWidth }} </p>
    <p> Window Height : {{ windowHeight }} </p>
  </div>



export default {
  data() {
    return {
      windowWidth : window.innerWidth,
      windowHeight : window.innerHeight
    };
  },
  methods : {
    handleResize() {
      this.windowWidth = window.innerWidth;
      this.windowHeight = window.innerHeight;
    }
  },
  mounted() {
    this.handleResize();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  }
}

In this component, we're initializing the `windowWidth` and `windowHeight` data properties with the initial window dimensions. The `handleResize` method updates these values whenever the window is resized.

The `mounted` hook is called when the component is mounted to the DOM, where we call `handleResize` to set the initial window size and add an event listener for the 'resize' event. This event listener triggers the `handleResize` method whenever the window size changes.

Remember to remove the event listener in the `beforeDestroy` hook to ensure clean up when the component is destroyed.

You can now include the `WindowSizeListener` component in any of your Vue templates to display and react to changes in the window size.

Vue

<div>
    
  </div>



import WindowSizeListener from './WindowSizeListener.vue';

export default {
  components : {
    WindowSizeListener
  }
}

With this setup, you can now easily retrieve and update the window size dynamically within your Vue.js application. Whether you need to adjust the layout, content, or any other aspect based on different screen sizes, this approach provides a simple and effective solution.

By implementing a window size listener in Vue.js, you can enhance the responsiveness and adaptability of your web applications for a better user experience across various devices and screen sizes.