跳到内容

templateRef

类别
导出大小
283 B
最后更改
4个月前

用于绑定 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.org.cn/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>>

源码

SourceDocs

贡献者

Anthony Fu
Anthony Fu
zhiyuanzmj
Hollis Wu
likeswinds
Alex Kozack
zhong666

更新日志

v12.0.0-beta.1 于 2024/11/21
0a9ed - feat!: 移除 Vue 2 支持,优化 bundles 并清理代码 (#4349)
v11.0.2 于 2024/8/24
acce3 - feat: 支持通过泛型参数指定允许的键 (#4162)

根据 MIT 许可证发布。