Lzh on GitHub

templateRef 是一个实用的函数,它提供了一种 将 Vue ref 绑定到模板元素 的简写方式。

用法

<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

在使用 JSX/TSX 时,templateRef 的用法稍有不同,需要显式返回 DOM 元素。

import { templateRef } from '@vueuse/core'

export default {
  setup() {
    const target = templateRef<HTMLElement | null>('target', null)
    
    // 使用字符串 ref
    return () => <div ref="target"></div>
  },
}

<script setup> 用法

在使用 <script setup> 时,通常不需要 templateRef,因为所有变量都会自动暴露给模板。在这种情况下,它的行为与标准的 ref 完全相同。

<script setup lang="ts">
import { ref } from 'vue'

const target = ref<HTMLElement | null>(null)
</script>

<template>
  <div ref="target" />
</template>

类型声明

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