useVueTemplateRef (JavaScript)
Summary
Section titled “Summary”- Rule available since:
v2.6.4 - Diagnostic Category:
lint/nursery/useVueTemplateRef - This rule doesn’t have a fix.
- The default severity of this rule is information.
- This rule belongs to the following domains:
- Sources:
- Inspired from
vue/prefer-use-template-ref
- Inspired from
How to configure
Section titled “How to configure”{ "linter": { "rules": { "nursery": { "useVueTemplateRef": "error" } } }}Description
Section titled “Description”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.
Examples
Section titled “Examples”Invalid
Section titled “Invalid”<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>Related links
Section titled “Related links”Copyright (c) 2023-present Biome Developers and Contributors.