Vue Template Refs: Reaching Past the Virtual DOM
Vue template refs give you a direct handle to a DOM element, bypassing the declarative model. This is for tasks like programmatically focusing an input or initializing a 3rd-party library. The main footgun: the ref is `null` until the component has mounted.
WHY IT EXISTS While Vue's declarative rendering is powerful, some tasks require direct interaction with browser DOM elements. For example, managing input focus, measuring an element's size, or integrating a vanilla JS library that needs a DOM node to attach to. Template refs provide this necessary bridge.
THE MENTAL MODEL Think of a template ref as a labeled anchor you drop into your HTML template. In your script, you create a variable with the same label. After Vue renders the component, it finds your anchor and connects your script variable directly to that live DOM element, giving you an 'escape hatch' to manipulate it imperatively.
HOW IT WORKS You add a special ref attribute to an element in your template, for example: <input ref="username">. In your script (using Composition API), you declare a ref with the same name, initialized to null: const username = ref(null). After the component mounts, Vue automatically assigns the actual DOM element to username.value. In the Options API, the reference is available via this.$refs.username.
WHEN TO USE IT Use template refs for tasks that cannot be done declaratively. Common use cases include: first, programmatically managing focus on an input element. Second, reading an element's dimensions or position for calculations. Third, initializing a third-party, non-Vue library on a specific element, like a charting library on a canvas.
WHEN NOT TO USE IT Avoid template refs for manipulations that Vue can handle declaratively. Do not use refs to manually change an element's text content, CSS classes, or styles. For these, always prefer data binding ({{ myData }}), class binding (:class), and style binding (:style). Overusing refs often means you are fighting against Vue's reactive system.
ONE CANONICAL EXAMPLE To automatically focus an input field when a component loads, first add the ref attribute in the template: <input ref="myInput">. In your <script setup>, import ref and onMounted from 'vue'. Declare const myInput = ref(null). Then, create the onMounted lifecycle hook and place the focus logic inside it: onMounted(() => { myInput.value.focus() }). Using onMounted is critical because it guarantees the element exists in the DOM before your code attempts to access it.
Read the original → vuejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.