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.dev.org.tw/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>>