vue get window width

To get the window width in Vue, you can follow these steps:

  1. Create a data property to store the window width:
data() {
  return {
    windowWidth: 0
  };
},
  1. Use the mounted lifecycle hook to set up an event listener for the resize event:
mounted() {
  window.addEventListener('resize', this.getWindowWidth);
},
  1. Define the getWindowWidth method to update the windowWidth data property with the current window width:
methods: {
  getWindowWidth() {
    this.windowWidth = window.innerWidth;
  }
},
  1. Invoke the getWindowWidth method once when the component is mounted to initialize the windowWidth data property:
mounted() {
  window.addEventListener('resize', this.getWindowWidth);
  this.getWindowWidth();
},
  1. Remember to remove the event listener when the component is destroyed to avoid memory leaks:
beforeDestroy() {
  window.removeEventListener('resize', this.getWindowWidth);
},

Now, the windowWidth data property will always hold the current window width. You can use it in your component's template or computed properties as needed.