Sometimes, we want to get the window size whenever it changes in a Vue.js app.
In this article, we’ll look at how to get the window size whenever it changes in a Vue.js app.
Get the Window Size Whenever it Changes in a Vue.js App
To get the window size whenever it changes in a Vue.js app, we can add resize
event listener to window
when the component is mounting.
For instance, we write:
<template>
<div id="app">{{ width }} x {{ height }}</div>
</template>
<script>
export default {
name: "App",
data() {
return { width: window.innerWidth, height: window.innerHeight };
},
created() {
window.addEventListener("resize", this.onResize);
},
destroyed() {
window.removeEventListener("resize", this.onResize);
},
methods: {
onResize(e) {
this.width = window.innerWidth;
this.height = window.innerHeight;
},
},
};
</script>
to call window.addEventListener
in the created
hook.
We use the onResize
method as the resize
event listener.
In the destroyed
hook, we call window.removeEventListener
to remove the event listener.
In onResize
and the data
methods, we get the width of the window with window.innerWidth
.
And we get the height of the window with window.innerHeight
.
Now when we resize the window, we should see the numbers change on the screen since we added width
and height
to the template.
Conclusion
To get the window size whenever it changes in a Vue.js app, we can add resize
event listener to window
when the component is mounting.
One reply on “How to Get the Window Size Whenever it Changes in a Vue.js App?”
Not sure if you can get window in created() cycle.