vue get window width
To get the window width in Vue, you can follow these steps:
- Create a data property to store the window width:
data() {
return {
windowWidth: 0
};
},
- Use the
mounted
lifecycle hook to set up an event listener for theresize
event:
mounted() {
window.addEventListener('resize', this.getWindowWidth);
},
- Define the
getWindowWidth
method to update thewindowWidth
data property with the current window width:
methods: {
getWindowWidth() {
this.windowWidth = window.innerWidth;
}
},
- Invoke the
getWindowWidth
method once when the component is mounted to initialize thewindowWidth
data property:
mounted() {
window.addEventListener('resize', this.getWindowWidth);
this.getWindowWidth();
},
- 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.