The way to use template references in the Vue 3 Composition API is to create responsive references through the ref function and bind to a template element or component. 1. Use the ref function to declare the variable and initialize it to null; 2. Bind the variable to the target element or component in the template; 3. After the component is mounted, the variable will automatically point to the corresponding DOM or component instance; 4. It is often used to operate the DOM, such as focus, drawing, etc.; 5. Be careful to avoid abuse of ref to modify the state, and it will become an array when used in v-for; 6. If used in functional components, the content needs to be explicitly exposed through context.expose.
Using template refs in Vue 3's Composition API is not complicated, but it is somewhat different from the Options API. You can create a responsive reference through the ref
function and bind it to an element or component in the template.
Create and bind Ref
In the Composition API, you need to declare a variable with the ref
function first, and then bind it to an element or component in the template. This variable starts with null
, and when the component is mounted, it will automatically point to the corresponding DOM element or component instance.
import { ref, onMounted } from 'vue' const inputEl = ref(null) onMounted(() => { // Here you can access the real DOM element inputEl.value.focus() })
Write it in the template like this:
<template> <input ref="inputEl" /> </template>
Note: ref
here is the variable name you just defined, not a string.
Use scenarios and precautions
Template references are most commonly used to manipulate DOM directly, such as manually focusing, scrolling to the bottom, getting element sizes, etc. Remember, however, try to avoid abuse of refs to "modify" data or state , which will make your code difficult to maintain.
Some common usage scenarios include:
- Automatically focus the input box after component is mounted
- Get the canvas element for drawing
- Manually control the behavior of third-party components (such as maps, rich text editors)
A few points to note:
- If you use ref in
v-for
, it will become an array containing all the corresponding elements - Do not give ref a different name from the variable in the template, otherwise it will not take effect.
- After the component is uninstalled, the value of ref will be cleared (set to null)
Use with functional components
If you are using functional components (without setup or script setup), you need to explicitly declare props
and context
and expose internal methods or properties through context.expose
so that the parent component can access the contents of the child component through ref.
However, in most cases, especially when using <script setup></script>
, Vue will automatically handle these details, you just need to declare the ref normally and bind it to the component as before.
Basically that's it. Just remember that ref is a variable that can point to a DOM or component instance, initialized to null, and there will be a value after mounting, and there will be no error.
The above is the detailed content of How to use template refs with Composition API?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Common mistakes to avoid Vue.js virtual DOM include: 1. Avoid unnecessary re-rendering, using watch or v-once optimization; 2. Use unique identifiers as keys, rather than indexes; 3. Avoid excessive use of watchers, prioritizing computed properties or methods; 4. Use lifecycle hooks correctly to ensure that the operation is carried out at the appropriate time.

View.jsandreactdififfertinVirtualDomimpement: View. oachwithreconciliation.1) View.jsminimizesre-rendersthroughdependencytracking, idealforsmallerapps.2) React’sfulltreecomparisonsuons

Vue.js uses virtual DOM to bring significant performance improvements and development experience optimization. 1) Virtual DOM reduces the number of real DOM operations and avoids redrawing and rearrangement. 2) Efficient algorithms compare new and old virtual DOM trees and only update the necessary parts. 3) The responsive system combines virtual DOM to accurately update the components that depend on data. 4) It is necessary to note that virtual DOM may introduce additional overhead, and applicable scenarios need to be carefully evaluated.

Vue.js efficiently handles updates through virtual DOM. The specific steps are as follows: 1) Generate a new virtual DOM tree when the component state changes; 2) compare with the old tree through the diffing algorithm to find the changed part; 3) Only update the changed DOM part. In practical applications, use v-if/v-show and key attributes to optimize performance, reduce unnecessary DOM operations, and improve user experience.

VueJSusesitsVirtualDOMforserver-siderendering(SSR)bycreatingaVirtualDOMtreeontheservertogenerateHTMLsenttotheclient.1)Theserverrenderstheinitialappstate,sendingafullyrenderedHTMLpage.2)TheVirtualDOMefficientlycomputeschangestogeneratethisHTML.3)Onthe

TheVirtualDOMinVue.jsenhancesperformanceandsimplifiesdevelopment.1)ItboostsperformancebyminimizingdirectDOMmanipulation.2)Itefficientlyupdatesbyusingadiffingalgorithm.3)Itsimplifiesdevelopmentthroughabstraction.4)ItintegrateswithVue.js'sreactivitysys

The key to optimizing Vue application performance is to start from four aspects: initial loading, responsive control, rendering efficiency and dependency management. 1. Use routes and components to lazy load, reduce the initial package volume through dynamic import; 2. Avoid unnecessary responsive data, and store static content with Object.freeze() or non-responsive variables; 3. Use v-once instructions, compute attribute cache and keep-alive components to reduce the overhead of repeated rendering; 4. Monitor the package volume, streamline third-party dependencies and split code blocks to improve loading speed. Together, these methods ensure smooth and scalable applications.

ToleverageVue.js'sVirtualDOMeffectively,followthesebestpractices:1)Usev-onceforstaticcontenttominimizeunnecessaryre-renders.2)Employcomputedpropertiesandwatcherswiselytoderivevaluesefficiently.3)Useuniquekeyswithv-forinliststomanageupdatesefficiently
