Skip to content

useCurrentElement

类别
导出大小
370 B
最近修改
2 days ago

获取当前组件的 DOM 元素作为引用。

🌐 Get the DOM element of current component as a ref.

示例

Open your console.log to see the element

用法

🌐 Usage

ts
import { 
useCurrentElement
} from '@vueuse/core'
const
el
=
useCurrentElement
() // ComputedRef<Element>

或者传递特定的 vue 组件

🌐 Or pass a specific vue component

vue
<script setup lang="ts">
import { 
useCurrentElement
,
VueInstance
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
componentRef
=
shallowRef
<
VueInstance
>(null as unknown as
VueInstance
)
const
el
=
useCurrentElement
(
componentRef
) // ComputedRef<Element>
</script> <template> <
div
>
<OtherVueComponent
ref
="
componentRef
" />
<
p
>Hello world</
p
>
</
div
>
</template>

注意事项

🌐 Caveats

该函数在内部使用了 $el

🌐 This functions uses $el under the hood.

在组件挂载之前,ref 的值将是 undefined

🌐 Value of the ref will be undefined until the component is mounted.

  • 对于具有单个根元素的组件,它将指向该元素。
  • 对于具有文本根的组件,它将指向文本节点。
  • 对于具有多个根节点的组件,它将是 Vue 用于跟踪组件在 DOM 中的位置的占位符 DOM 节点。

建议仅将此功能用于具有单个根元素的组件。

🌐 It's recommend to only use this function for components with a single root element.