useCurrentElement
useCurrentElement
現在のコンポーネントのDOM要素をrefとして取得します。
使用法
import { useCurrentElement } from '@vueuse/core'
const el = useCurrentElement() // ComputedRef<Element>
または特定の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ノードになります。
単一のルート要素を持つコンポーネントに対してのみこの関数を使用することをお勧めします。
© 2019–PRESENT Anthony Fu https://github.com/antfu
※このページは Nuxt.js 公式ドキュメントの翻訳ページです。
公式ドキュメントの該当ページはこちら:
#