Skip to content

useVueTemplateRef (JavaScript)

Language JavaScript (and super languages)
biome.json
{
"linter": {
"rules": {
"nursery": {
"useVueTemplateRef": "error"
}
}
}
}

Require useTemplateRef() instead of ref() or shallowRef() to access elements of the template.

A template ref gives your script access to an element or a child component of the template. You name the element with the ref attribute, as in <input ref="input" />.

In <script setup>, Vue fills in a variable created with ref() or shallowRef() when the variable has the same name as a ref attribute. The link between the two is only the name, so renaming the variable silently breaks it. The variable also looks like any other piece of state, which makes it hard to tell that the template fills it in.

Vue 3.5 added useTemplateRef(), which takes the name of the ref attribute as an argument. The variable can then have any name, and the call shows that the value comes from the template.

This rule reports a variable declared at the top level of <script setup> with ref() or shallowRef() when an element of the template has a ref attribute with the same name.

A ref attribute with a dynamic value, such as :ref="(el) => (input = el)", isn’t reported, because the function decides where the element is stored.

<template>
<input ref="input" />
</template>
<script setup>
import { ref } from "vue";
const input = ref();
</script>
<template>
<div ref="root" />
</template>
<script setup>
import { shallowRef } from "vue";
const root = shallowRef(null);
</script>
<template>
<input ref="input" />
<button :ref="(el) => (button = el)">Send</button>
</template>
<script setup>
import { ref, useTemplateRef } from "vue";
const inputElement = useTemplateRef("input");
const button = ref();
</script>