Nuxt3中从布局获取Ref到组件,如何正确调用getBoundingClientRect?
解决Nuxt3中子组件获取布局元素Bounding的问题
问题根源
你遇到的报错是因为以下几个问题:
- Provide使用错误:你直接将ref对象作为
provide的第一个参数,没有指定字符串类型的注入key,导致子组件inject('footergrid')无法拿到正确的元素引用。 - 未处理SSR与元素挂载时机:Nuxt3是服务端渲染框架,服务器端不存在DOM;同时元素未挂载时,ref的值为
undefined,直接调用useElementBounding会因参数不是有效DOM元素报错。 - 多余的reactive包裹:
useElementBounding本身已返回响应式对象,无需再用reactive二次包裹。
修复方案及代码示例
1. 布局组件修正
正确使用provide,指定注入key和对应的ref值:
<template> <footer ref="footergrid"> <some-other-component /> </footer> <child-comp /> </template> <script setup> import { ref, provide } from 'vue' const footergrid = ref() // 第一个参数为注入key,第二个为要传递的元素ref provide('footergrid', footergrid) </script>
2. 子组件修正
在元素挂载完成的客户端环境中,调用useElementBounding:
<script setup> import { useElementBounding, onMounted } from '@vueuse/core' import { inject } from 'vue' const extfootergrid = inject('footergrid') let footergridBounds = null onMounted(() => { // 确保在客户端且元素已挂载 if (process.client && extfootergrid.value) { footergridBounds = useElementBounding(extfootergrid) console.log(footergridBounds) } }) </script>
内容的提问来源于stack exchange,提问作者flexicon
相关产品推荐
相关产品推荐

