INFO
This function will be removed in future version.
Vue 3.5 introduced the useTemplateRef API which can effectively replace the functionality of templateRef, therefore we recommend using the native approach.
templateRef
将 ref 绑定到模板元素的简写方式。
用法
vue
<script lang="ts">
import { templateRef } from '@vueuse/core'
export default {
setup() {
const target = templateRef('target')
// 无需返回 `target`,它将奇迹般地绑定到 ref 上
},
}
</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>类型声明
ts
/**
* @deprecated Use Vue's built-in `useTemplateRef` instead.
*
* Shorthand for binding ref to template element.
*
* @see https://vueuse.org/templateRef
* @param key
* @param initialValue
*
* @__NO_SIDE_EFFECTS__
*/
export declare function templateRef<
T extends HTMLElement | SVGElement | Component | null,
Keys extends string = string,
>(key: Keys, initialValue?: T | null): Readonly<Ref<T>>