templateRef
テンプレート要素に 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>>