We may sometimes need to know the screen width (viewport) of the application. We can easily do that by attaching an event listener to the resize event in our Vue app as follows:
<template>
<div id="app">
<p>Screen width: {{ screenWidth }}px</p>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
screenWidth: 0,
};
},
mounted() {
this.updateScreenWidth();
this.onScreenResize();
},
methods: {
onScreenResize() {
window.addEventListener("resize", () => {
this.updateScreenWidth();
});
},
updateScreenWidth() {
this.screenWidth = window.innerWidth;
},
},
};
</script>
<style>
#app {
text-align: center;
margin-top: 60px;
}
</style>
Code language: HTML, XML (xml)
In the above code we’ve taken a reactive state named screenWidth with a default value of 0. As soon as the app is mounted, we update its value from the window object using window.innerWidth. We then call the onScreenResize method immediately after it. In this method, we attach an event listener to the resize event. Whenever we resize the window, this method will be called. We’ve updated the screenWidth inside the method.
You can find a working version of the above code from my repo links below: