Skip to content

useCurrentElement

Category
Export Size
355 B
Last Changed
last week

Get the DOM element of current component as a ref.

Demo

Open your console.log to see the element

Usage

ts
import { useCurrentElement } from '@vueuse/core'

const el = useCurrentElement() // ComputedRef<Element>

Or pass a specific vue component

vue
<script setup>
import { useCurrentElement } from '@vueuse/core'
import { ref } from 'vue'

const componentRef = ref()

const el = useCurrentElement(componentRef) // ComputedRef<Element>
</script>

<template>
  <div>
    <OtherVueComponent ref="componentRef" />
    <p>Hello world</p>
  </div>
</template>

INFO

Only works for Vue 3 because it uses computedWithControl under the hood

Caveats

This functions uses $el under the hood.

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.
  • 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.

Type Declarations

typescript
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>

Source

SourceDemoDocs

Contributors

Anthony Fu
Anthony Fu
山吹色御守
Jessé Correia Lins
vaakian X

Changelog

v12.0.0-beta.1 on 11/21/2024
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v11.1.0 on 9/16/2024
8e141 - feat: try to infer type from $el (#4202)
v10.8.0 on 2/20/2024
0a9aa - feat: Allow get current element from a specific component (#3750)

Released under the MIT License.