How to access DOM elements in Vue using template refs?
In Vue, template ref is a way to directly access DOM elements or child component instances. By using the ref attribute in the template, Vue will expose the element or component instance in the $refs object; 1. ref is a special attribute, attached to the element or component; 2. $refs will be populated only after the component rendering is completed; 3. Can be used for native elements and custom components; 4. Commonly used for manual focus, animation triggering, integration of third-party libraries, and access to child component methods; 5. Note that $refs is not responsive and should not be used in templates or computed attributes; 6. Avoid abuse in v-for, nor should it be accessed during rendering; 7. When using Composition API in Vue 3, it can be bound through the ref function; 8. Use it with caution, and priority is given to maintaining the declarative style of the code.
In Vue, accessing DOM elements directly is something you typically avoid in favor of declarative data binding. But sometimes, like when working with focus, animations, or third-party libraries, you really do need to get your hands on a DOM node. That's where template refs come in handy.

Vue gives you a clean way to access DOM elements or component instances using the ref
attribute in templates. It's straightforward, but there are a few gotchas to be aware of.
What are template refs and how do you use them?
In Vue, a ref
is a special attribute you can attach to an element or component inside your template. When the component is rendered, Vue will expose that element or component instance via the $refs
object.

Here's a basic example:
<template> <input ref="myInput" type="text" /> </template> <script> export default { mounted() { // Access the DOM element this.$refs.myInput.focus(); } } </script>
In this case, myInput
becomes a key in this.$refs
, and its value is the actual DOM element. This works for both HTML elements and custom components.

A few things to note:
-
ref
is only popular after the component has been rendered. - Don't overuse
$refs
— they're meant for one-off access, not reactive data flow. - You can use
ref
on both native elements and custom components.
When should you use template refs?
You'll typically reach for ref
when Vue's reactivity system isn't enough for what you need. Common scenarios include:
- Manually focusing an input after render.
- Triggering important animations.
- Integrating with non-Vue libraries that require DOM access.
- Accessing methods or properties on child components.
For example, imagine you want to focus a search input when a modal opens. You can't do that declaratively — you need to call .focus()
at the right time.
Another use case is calling a method on a child component:
<template> <MyComponent ref="childComponent" /> </template> <script> export default { mounted() { this.$refs.childComponent.someMethod(); } } </script>
Just remember: $refs
aren't reactive. Don't use them in templates or computed properties.
Common pitfalls and best practices
Using template refs is simple, but it's easy to misuse them. Here are a few things to watch out for:
- Avoid using
$refs
in loops : If you useref
inside av-for
, it becomes an array of elements. That can work, but it's easy to break if the list changes. - Don't access
$refs
during render : They may not be available yet. Stick tomounted()
orupdated()
hooks. - Don't overuse them : If you find yourself using
$refs
often, consider if there's a more Vue-friendly way using data binding or events.
Also, keep in mind that with Vue 3 and the Composition API, the way you use ref
changes a bit — you can use the ref
function and bind it directly instead of relying on $refs
.
Summary
Template refs in Vue are a practical tool for direct DOM access or interacting with child components. Use them sparingly, and always keep your code declarative where possible. Once you understand when and how to use them, they're a solid part of your Vue toolkit.
Basically that's it.
The above is the detailed content of How to access DOM elements in Vue using template refs?. 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)

Environment variable management is crucial in Vue projects and you need to choose the right way based on the build tool. 1. The VueCLI project uses the .env file with VUE_APP_ prefix, accessed through process.env.VUE_APP, such as .env.production; 2. The Vite project uses the VITE_ prefix, accessed through import.meta.env.VITE_, such as .env.staging; 3. Both support custom mode to load corresponding files, and the .env.local class file should be added to .gitignore; 4. Always avoid exposing sensitive information on the front end, provide .env.example for reference, and check it at runtime.

Install ApolloClient and related dependency packages and configure the client according to Vue2 or Vue3; 2. Provide client instances in Vue3 through provideApolloClient, and use VueApollo plug-in in Vue2; 3. Use the combined API of useQuery and useMutation to initiate queries and changes in components; 4. Use variables and refetch to achieve dynamic data acquisition and refresh, optional polling and updates; 5. Use loading and error state to optimize user experience, and combine Suspense or anti-shake to improve interaction fluency; 6. Add authentication information through HTTP link headers, and use caches, fragments and query files to organize and provide

Usecomputedpropertieswhenderivingreactivevaluesfordisplay,astheyarecachedandonlyre-evaluatewhendependencieschange;2.UsewatchforexecutingsideeffectslikeAPIcallsorupdatingstorageinresponsetodatachanges,sincewatchersreacttovaluechangesandsupportasyncope

Functional components are used in Vue2 to create stateless, high-performance presentation components, suitable for scenarios that rely only on props. 1. To define functional:true, you need to set functional:true to receive props and context through the render function to return VNode. 2. Register and pass in props and events like normal components when used. 3. To handle slots, you need to get slots() and children from the context. Functional components are not suitable for scenarios where responsive data, lifecycle hooks, or v-models are required. Vue3 has removed the functional option and replaced it with functional writing or concise combination components. Performance optimization depends more on Comp

TeleportinVue3allowsrenderingacomponent'stemplateinadifferentDOMlocationwhilepreservingitslogicalpositioninthecomponenttree;1.ItusesthecomponentwithatoattributespecifyingthetargetDOMnode,suchas"body"or"#modal-root";2.Theteleported

Create a mobile application using VueNative is an effective way to achieve cross-platform development using Vue.js syntax combined with ReactNative; 2. First configure the development environment, install Node.js and ExpoCLI, and create a project through the command npxcreate-react-native-appmy-vue-app--templatevue-native; 3. Enter the project directory and run npmstart, scan the QR code through the ExpoGo application to preview it on the mobile device; 4. Write the .vue file components, use and structure, and pay attention to using lowercase ReactNative components such as view, text and buttons in lowercase

Use Vite to create a Vue3 project that supports TypeScript; 2. Use defineComponent to provide type inference; 3. Use simplified code; 4. Use interfaces or types to define props; 5. Use type joint to correctly declare emits; 6. Use generics in composable functions; 7. Use InjectionKey to type provide/inject—through these steps, you can realize type-safe and maintainable Vue3 TypeScript applications, and finally build a powerful and extensible front-end project.

Installing Storybook can be done automatically through npxstorybook@latestinit, or manually install dependencies and configure .storybook/main.js and preview.js; 2. Write story files (such as Button.stories.js) to define different states of components, and use Template binding parameters to generate multiple instances; 3. Use Args and Controls to achieve dynamic attribute adjustments to improve interactive testing efficiency; 4. Integrate documents and stories through MDX files to enhance readability and collaboration; 5. It is recommended to co-locate story files with components, adopt CSF format, integrate Chromatic for visual regression testing, and use decoration
