Skip to content

useCurrentElement

获取当前组件的 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.

  • 对于具有单个根元素的组件,它将指向该元素。

    ¥For components with a single root element, it will point to that element.

  • 对于具有文本根的组件,它将指向文本节点。

    ¥For components with text root, it will point to the text node.

  • 对于具有多个根节点的组件,它将是 Vue 用于跟踪组件在 DOM 中的位置的占位符 DOM 节点。

    ¥For components with multiple root nodes, it will be the placeholder DOM node that Vue uses to keep track of the component's position in the DOM.

建议仅对具有单个根元素的组件使用此函数。

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