Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue 3 ref Attribute

Vue 3 ref Attribute

Vue3 Built-in Properties Vue 3 Built-in Attributes


ref The ref attribute is used to register reference information for an element or child component, so you can directly access the DOM element or component instance in JavaScript code.


Basic Explanation

ref ref is an important way to get DOM elements or component instances in Vue. It allows us to directly manipulate the DOM or call child component methods after the Vue instance is mounted.


Basic Usage

1. Using ref in Options API

In the Options API, the references registered by ref are stored in the component instance's $refs object:

Example

2. Using ref in Composition API

In the Composition API, it is recommended to use useTemplateRef to get template references:

Example


Use Cases

1. Access DOM Elements

Using ref you can directly access DOM elements for operations such as focus control and getting values:

Example

2. Access Child Component Instances

Using ref you can access child component instances, calling child component methods or accessing their data:

Example

3. Function Refs

ref can also accept a function, which is called on each update, giving you full control over where the reference is stored:

Example


Notes

ref Registration Timing: Because ref itself is created from the render function's result, it must be accessed after the component is mounted. If you access it in created lifecycle hook,$refs it will still be an empty object.

Non-reactive:$refs is non-reactive, so it should not be used for data binding in templates. Use it only in JavaScript for DOM operations.

Avoid Overusing ref: Operate on the DOM and child components through data-driven approaches and event handling as much as possible. Overusing ref makes code hard to maintain.

Example


Used with v-for

ref can also be used with v-for, creating an array containing all corresponding DOM elements or component instances:

Example