Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

In Vue JS, the window size can be retrieved using the following method:

  1. Create a data property to hold the window size.

    data() {
     return {
       windowSize: {
         width: window.innerWidth,
         height: window.innerHeight
       }
     };
    }
    
  2. Add an event listener to the mounted hook to update the window size when it is resized.

    mounted() {
     window.addEventListener("resize", this.getWindowSize);
    },
    beforeDestroy() {
     window.removeEventListener("resize", this.getWindowSize);
    },
    methods: {
     getWindowSize() {
       this.windowSize = {
         width: window.innerWidth,
         height: window.innerHeight
       };
     }
    }
    
  3. Use the windowSize property wherever it is needed in the Vue component.

    <template>
     <div>
       <p>Window Width: {{ windowSize.width }}</p>
       <p>Window Height: {{ windowSize.height }}</p>
     </div>
    </template>