美文网首页
ResizeObserver loop completed wi

ResizeObserver loop completed wi

作者: 蓦然回味 | 来源:发表于2024-03-31 11:33 被阅读0次

    Vue

    ResizeObserver loop completed with undelivered notifications.
    at handleError (webpack-internal:///./node_modules/webpack-dev-server/client/overlay.js:299:58)
    at eval (webpack-internal:///./node_modules/webpack-dev-server/client/overlay.js:318:7)

    ResizeObserver loop completed with undelivered notifications 这个警告信息通常表示 ResizeObserver 在其回调函数中花费了太多时间,导致浏览器无法及时传递所有的尺寸变化通知。这可能是因为回调函数执行了复杂的计算或耗时的操作,使得浏览器无法及时响应其他的尺寸变化。

    在编写使用 ResizeObserver 的代码时,你应该确保回调函数尽可能高效,避免执行耗时的任务。如果需要在回调函数中执行复杂的逻辑,你可以考虑使用异步操作(如 setTimeout 或 requestAnimationFrame)来延迟执行,以避免阻塞浏览器的事件循环。

    以下代码解释了如何避免这个问题:

    <template>  
      <div ref="resizableElement">  
        <!-- 组件内容 -->  
      </div>  
    </template>  
      
    <script>  
    export default {  
      data() {  
        return {  
          resizeObserver: null,  
        };  
      },  
      mounted() {  
        this.resizeObserver = new ResizeObserver(entries => {  
          // 使用 requestAnimationFrame 来异步处理尺寸变化逻辑  
          // 这样可以避免阻塞事件循环  
          requestAnimationFrame(() => {  
            entries.forEach(entry => {  
              const { width, height } = entry.contentRect;  
                
              // 在这里编写处理尺寸变化的逻辑  
              console.log('Element resized:', width, height);  
                
              // 更新组件状态或其他操作  
              this.updateComponentStateBasedOnSize(width, height);  
            });  
          });  
        });  
          
        // 开始观察尺寸变化  
        this.resizeObserver.observe(this.$refs.resizableElement);  
      },  
      beforeUnmount() {  
        // 组件卸载前断开观察器连接  
        if (this.resizeObserver) {  
          this.resizeObserver.disconnect();  
        }  
      },  
      methods: {  
        updateComponentStateBasedOnSize(width, height) {  
          // 更新组件状态或其他操作  
          // 确保这些操作不会阻塞事件循环  
          this.newWidth = width;  
          this.newHeight = height;  
        }  
      },  
    };  
    </script>
    
    

    在这个修改后的代码中,我使用了 requestAnimationFrame 来异步执行处理尺寸变化的逻辑。requestAnimationFrame 会告诉浏览器你希望执行一个动画,并请求浏览器在下一次重绘之前调用指定的回调函数来更新动画。这通常用于创建平滑的动画效果,但也可以用于任何需要在下一个渲染周期中执行的任务,以避免阻塞。

    通过将处理尺寸变化的逻辑放在 requestAnimationFrame 的回调函数中,你可以确保浏览器有足够的时间来处理其他事件和尺寸变化通知,从而避免 ResizeObserver loop completed with undelivered notifications 的警告。

    此外,你还需要确保 updateComponentStateBasedOnSize 方法中的操作不会过于复杂或耗时。如果确实需要执行复杂的逻辑,你可以考虑将其分解为更小的部分,或者使用 Web Workers 在后台线程中执行这些操作。

    总之,要避免 ResizeObserver 的警告信息,你需要确保回调函数的执行尽可能高效,并避免阻塞浏览器的事件循环。

    相关文章

      网友评论

          本文标题:ResizeObserver loop completed wi

          本文链接:https://www.haomeiwen.com/subject/glavtjtx.html