跳到主要內容

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.dev.org.tw/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

更新日誌 🔗

v12.0.0-beta.1 於 2024/11/21
0a9ed - feat!: 移除 Vue 2 支援,優化 bundles 並清理 (#4349)
v11.0.2 於 2024/8/24
acce3 - feat: 支援透過泛型引數指定允許的鍵 (#4162)

在 MIT 許可證下發布。