In Vue.js, you can use the window.onresize
event to detect changes in the size of the browser window, and update the state of your component accordingly. Here's an example:
<template>
<div>
<p>Window Width: {{ windowWidth }}</p>
<p>Window Height: {{ windowHeight }}</p>
</div>
</template>
<script>
export default {
data() {
return {
windowWidth: 0,
windowHeight: 0
};
},
mounted() {
// Add an event listener for window resize
window.addEventListener('resize', this.handleResize);
// Call the resize handler once to initialize the state
this.handleResize();
},
destroyed() {
// Remove the event listener when the component is destroyed
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
// Update the window width and height in the component state
this.windowWidth = window.innerWidth;
this.windowHeight = window.innerHeight;
}
}
};
</script>
In this example, we define a component that displays the current width and height of the browser window. We use the data
function to define two reactive properties windowWidth
and windowHeight
that store the current dimensions of the window.
We then use the mounted
lifecycle hook to add an event listener for the resize
event on the window
object. The event listener calls the handleResize
method, which updates the windowWidth
and windowHeight
properties based on the current size of the window.
We also call the handleResize
method once during initialization to set the initial state of the component.
Finally, we use the destroyed
lifecycle hook to remove the event listener when the component is destroyed, to avoid memory leaks.
With this code, your component will automatically update the window dimensions whenever the browser window is resized.
Comments
Post a Comment