Vue 3 ref Attribute
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.
- Type: String | Function
- Purpose: Access DOM elements or child component instances to perform focus control, method calls, and other operations.
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
Focus input box
2. Using ref in Composition API
In the Composition API, it is recommended to use useTemplateRef to get template references:
Example
Focus input box
Use Cases
1. Access DOM Elements
Using ref you can directly access DOM elements for operations such as focus control and getting values:
Example
Get value
2. Access Child Component Instances
Using ref you can access child component instances, calling child component methods or accessing their data:
Example
Call child component method
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
Focus
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
createdlifecycle hook,$refsit will still be an empty object.
Non-reactive:
$refsis 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
Vue 3 Built-in Attributes