Vue3 Setup Ref

Posted on  by admin
In this Vue tutorial we learn how to access DOM nodes directly from within Vue and use lifecycle methods to manipulate it.

We cover how to define and access refs on both elements and entire component instances. If you want to follow along with the examples, you will need an app generated by the Vue CLIas well as the following extra component. The project should look similar to the following. The root App component imports and uses theTemplateRefcomponent.

Lesson Project

TheTemplateRefcomponent can just show an identifying message in a paragraph to start with. Template Refs make it possible to access DOM nodes directly from within Vue. As an example, let’s say we have a login form and want to focus the email/username field when the page loads.

Template refs on components

We can access the input with a template ref and focus it in a lifecycle method.
We define a template ref with therefattribute, which will register a new reference to an element or component.
It’s value is an identifier that we use later on to access the reference.

How to define a template ref

As an example, let’s create a text field in ourTemplateRefcomponent with a ref calledtextInputRef. We’ll also add a focus CSS style to help the demonstration. To access a template ref, we use the$refsinstance variable with the identifier we assigned to it.

As an example, let’s access our textInputRef and chain thefocusmethod to it in the mounted lifecyclehook.

What are Template Refs?

The method will set the text input to a focussed state when the component is mounted.

How to access a template ref

If we save the file and reload the page in the browser, the text input will show a blue outline, indicating that it has focus. We mentioned earlier thatrefcan be used on a component as well.