Skip to content
On this page

templateRef

Category
Last Changed
7 months ago

Shorthand for binding ref to template element.

Usage

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

import { templateRef } from '@vueuse/core'

export default {
  setup() {
    const target = templateRef<HTMLElement | null>('target', null)

    // use string ref
    return () => <div ref="target"></div>
  },
}
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.

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

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

<template>
  <div ref="target" />
</template>
<script setup lang="ts">
import { ref } from 'vue'

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

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

Type Declarations

/**
 * Shorthand for binding ref to template element.
 *
 * @see https://vueuse.org/templateRef
 * @param key
 * @param initialValue
 */
export declare function templateRef<T extends HTMLElement | SVGElement | null>(
  key: string,
  initialValue?: T | null
): Readonly<Ref<T>>
/**
 * Shorthand for binding ref to template element.
 *
 * @see https://vueuse.org/templateRef
 * @param key
 * @param initialValue
 */
export declare function templateRef<T extends HTMLElement | SVGElement | null>(
  key: string,
  initialValue?: T | null
): Readonly<Ref<T>>

Source

SourceDocs

Contributors

Anthony Fu
likeswinds
Alex Kozack
zhong666

Changelog

v7.5.1 on 12/31/2021
c6abd - fix: stricter eslint rules
v6.6.0 on 10/16/2021
e9677 - fix: improve types (#831)
templateRef has loaded