Skip to content

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

类别
导出体积
283 B
上次更改
2 days ago

将 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>

类型声明

typescript
/**
 * @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>>

源码

源码文档

贡献者

Anthony Fu
一纸忘忧
Anthony Fu
SerKo
IlyaL
zhiyuanzmj
Hollis Wu
likeswinds
Alex Kozack
zhong666

更新日志

0271e - feat: mark templateRef as deprecated (#4894)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
acce3 - feat: support specifying allowed keys via generic argument (#4162)