Skip to content

templateRef

类别
导出体积
270 B
上次更改
2 weeks 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
/**
 * Shorthand for binding ref to template element.
 *
 * @see https://vueuse.org/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

更新日志

v11.0.2 on 8/24/2024
acce3 - feat: support specifying allowed keys via generic argument (#4162)
v9.3.0 on 9/26/2022
cd798 - fix: add Component type (#2203)