Skip to content

useCurrentElement

类别
导出体积
365 B
上次更改
9 months ago

将当前组件的 DOM 元素作为 ref 返回。

示例

打开console.log查看元素

用法

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

或者传递一个特定的 Vue 组件

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>

注意事项

此函数在底层使用 $el

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

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

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

类型声明

ts
export declare function 
useCurrentElement
<
T
extends
MaybeElement
=
MaybeElement
,
R
extends
VueInstance
=
VueInstance
,
E
extends
MaybeElement
=
MaybeElement
extends
T
?
IsAny
<
R
["$el"]> extends false
?
R
["$el"]
:
T
:
T
,
>(
rootComponent
?:
MaybeElementRef
<
R
>):
ComputedRefWithControl
<
E
>

源码

源码演示文档

贡献者

一纸忘忧
Anthony Fu
Anthony Fu
David Gonzalez
James Garbutt
IlyaL
山吹色御守
Jessé Correia Lins
vaakian X

更新日志

59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
8e141 - feat: try to infer type from $el (#4202)
0a9aa - feat: Allow get current element from a specific component (#3750)