Skip to content

templateRef ​

Category
Export Size
270 B
Last Changed
yesterday

Shorthand for binding ref to template element.

Usage ​

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>

With 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> ​

There is no need for this when using with <script setup> since all the variables will be exposed to the template. It will be exactly the same as ref.

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

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

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

Type Declarations ​

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

Source ​

Source • Docs

Contributors ​

Anthony Fu
Anthony Fu
zhiyuanzmj
Hollis Wu
likeswinds
Alex Kozack
zhong666

Changelog ​

v12.0.0-beta.1 on 11/21/2024
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
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)

Released under the MIT License.