Skip to content

What Is a Template Ref in Vue?

In Vue, the ref attribute keeps references to components or DOM elements. It can be used on Vue components or plain HTML elements and gives JavaScript direct access to them. Used in a template, it reaches DOM elements or component instances outside Vue's declarative rendering.

The main uses of ref:

  1. Accessing DOM elements: add a ref attribute to an HTML element and reach it through this.$refs on the Vue instance. For example, with <input ref="myInput"> you can reach the input with this.$refs.myInput.
  2. Accessing component instances: if ref is used on a Vue component, this.$refs gives you that component's instance, so you can call its methods or read its data directly.
  3. Not reactive: refs are not reactive; when the referenced element changes, Vue's reactivity system is not notified.
  4. Component lifecycle: referenced elements and components are available according to the lifecycle — for example you can reach a DOM element through its ref once the component is mounted.

Refs are useful for DOM manipulation or direct interaction with child components, but within Vue's reactive, declarative rendering model it is best to keep their use limited.

Note (Vue 3): With <script setup>, a template ref is a ref with the same name: const myInput = ref(null) receives the element after mounting, for example in onMounted(() => myInput.value.focus()). Vue 3.5 also adds useTemplateRef('myInput').

Have a question about this article? Write to me