乐闻世界logo
搜索文章和话题

How vuejs retrieves window size when it changes

1个答案

1

In Vue.js, you can listen for changes in window size and retrieve the window dimensions using multiple approaches. Below, I will provide a detailed explanation of one commonly used method along with the corresponding example code.

Method: Using the resize Event of window

Within Vue components, you can utilize the JavaScript resize event to monitor window size changes. This event triggers whenever the window size is altered. You should add event listeners in the mounted hook and remove them in the beforeDestroy hook to prevent memory leaks.

Example Code:

vue
<template> <div> <h1>Current window width: {{ windowWidth }}</h1> </div> </template> <script> export default { data() { return { windowWidth: window.innerWidth }; }, methods: { handleResize() { // Update window width this.windowWidth = window.innerWidth; } }, mounted() { // After component mounting, add resize event listener window.addEventListener('resize', this.handleResize); }, beforeDestroy() { // Before component destruction, remove resize event listener window.removeEventListener('resize', this.handleResize); } }; </script> <style> /* Your style code */ </style>

Explanation:

  1. Data Definition: The windowWidth data property is defined in the data function to store the current window width.
  2. Method Definition: The handleResize method updates the windowWidth value to reflect the current window width.
  3. Event Listening and Removal:
    • In the mounted hook, addEventListener is used to attach a resize event listener to the window object, with handleResize specified as the event handler.
    • In the beforeDestroy hook, removeEventListener is used to detach the previously added resize event listener, which is a critical step to prevent memory leaks.

By implementing this method, your Vue application can respond in real-time to browser window size changes and display the current window width on the page. This technique is highly valuable for developing responsive layouts or applications that dynamically adjust content based on window size.

2024年8月24日 18:06 回复

你的答案