コンテンツにスキップ

templateRef

カテゴリ
エクスポートサイズ
270 バイト
最終変更日
先週

テンプレート要素に ref をバインドするための簡略表記です。

使用方法

vue
<script lang="ts">
import { templateRef } from '@vueuse/core'

export default {
  setup() {
    const target = templateRef('target')

    // no need to return the `target`, it will bind to the ref magically
  },
}
</script>

<template>
  <div ref="target" />
</template>

JSX/TSXを使用する場合

tsx
import { templateRef } from '@vueuse/core'

export default {
  setup() {
    const target = templateRef<HTMLElement | null>('target', null)

    // use string ref
    return () => <div ref="target"></div>
  },
}

<script setup>

<script setup> を使用する場合、すべての変数がテンプレートに公開されるため、これは必要ありません。 ref と全く同じになります。

vue
<script setup lang="ts">
import { ref } from 'vue'

const target = ref<HTMLElement | null>(null)
</script>

<template>
  <div ref="target" />
</template>

型宣言

typescript
/**
 * Shorthand for binding ref to template element.
 *
 * @see https://vueuse.dokyumento.jp/templateRef
 * @param key
 * @param initialValue
 */
export declare function templateRef<
  T extends HTMLElement | SVGElement | Component | null,
  Keys extends string = string,
>(key: Keys, initialValue?: T | null): Readonly<Ref<T>>

ソース

ソースドキュメント

貢献者

Anthony Fu
Anthony Fu
zhiyuanzmj
Hollis Wu
likeswinds
Alex Kozack
zhong666

変更履歴

v12.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2 のサポートをドロップし、バンドルを最適化し、クリーンアップする (#4349)
v11.0.2 2024/8/24
acce3 - feat: ジェネリック引数で許可されるキーを指定できるようにする (#4162)
v9.3.0 2022/9/26
cd798 - fix: コンポーネントタイプを追加 (#2203)

MITライセンスでリリースされています。