Vue Template Refs & Lifecycle
Estimated reading: 4 minutes 29 views

πŸ” Vue Template Refs – Directly Access DOM Elements and Components (2025 Guide)


🧲 Introduction – What Are Template Refs in Vue?

Template refs in Vue.js allow you to directly reference DOM elements or child components inside your component logic. This is especially useful when you need fine-grained control over the DOM, such as focusing an input, measuring an element, or interacting with component methods.

🎯 In this guide, you’ll learn:

  • What Vue refs are and how to use them
  • How to reference DOM nodes and child components
  • How to use ref with the Composition API
  • Practical examples with step-by-step code

πŸ“˜ What Is a Template Ref?

A template ref is a way to assign an identifier to an element or component in the template so you can access it in JavaScript.

<input ref="myInput" />

Then in your script:

this.$refs.myInput.focus();

🧱 Example – Accessing DOM with ref

βœ… Focusing an Input Field

<template>
  <div>
    <input ref="searchBox" placeholder="Type here..." />
    <button @click="focusInput">Focus</button>
  </div>
</template>

<script>
export default {
  methods: {
    focusInput() {
      this.$refs.searchBox.focus();
    }
  }
}
</script>

🧠 ref="searchBox" makes the input accessible via this.$refs.searchBox.


πŸ”— Refs with Child Components

You can also use ref to call methods or access data in child components.

βœ… Child Component

<template><button @click="alertMessage">Say Hi</button></template>

<script>
export default {
  methods: {
    alertMessage() {
      alert('Hello from child!');
    }
  }
}
</script>

βœ… Parent Component

<template>
  <ChildComp ref="childRef" />
  <button @click="callChildMethod">Trigger Child</button>
</template>

<script>
import ChildComp from './ChildComp.vue';

export default {
  components: { ChildComp },
  methods: {
    callChildMethod() {
      this.$refs.childRef.alertMessage();
    }
  }
}
</script>

🧠 Great for creating interactive dashboards and modular UI interactions.


🧬 Template Refs with Composition API

Use ref() from Vue’s reactivity system along with onMounted().

<template>
  <input ref="inputEl" placeholder="Enter something..." />
</template>

<script setup>
import { ref, onMounted } from 'vue';

const inputEl = ref(null);

onMounted(() => {
  inputEl.value.focus();
});
</script>

🧠 ref(null) sets up a reactive reference. The actual DOM element is assigned after mount.


🧰 Real-World Use Cases

Use CaseHow Refs Help
Focusing form inputsinputRef.focus()
Accessing component methodschildRef.methodName()
Getting DOM size/positionelementRef.getBoundingClientRect()
Manual animationsDirect DOM manipulation for performance

⚠️ Best Practices for Template Refs

TipWhy It Matters
Use refs only when necessaryAvoid bypassing Vue’s reactivity
Always check if ref is not nullDOM may not be ready in lifecycle hook
Don’t mutate DOM via refs unnecessarilyLet Vue handle rendering where possible
Prefer props and events for component commRefs are for edge cases, not communication

πŸ“Œ Summary – Recap & Next Steps

Template refs in Vue provide a powerful way to manipulate the DOM or interact with components directly. While Vue promotes declarative logic, refs serve well in cases where direct access is essential.

πŸ” Key Takeaways:

  • Use ref="name" in templates to assign references
  • Access with this.$refs.name (Options API) or ref() (Composition API)
  • Ideal for DOM tasks like focus, scroll, or dimension measuring
  • Use sparingly and wisely to maintain clean architecture

βš™οΈ Real-World Relevance:
Template refs are essential in modals, form handling, dynamic layouts, and custom UI widgets.


❓ FAQ Section

❓ What is a ref in Vue?

βœ… It’s a way to reference a DOM element or component instance from within your component logic.


❓ How do I use ref in Vue 3 Composition API?

βœ… Use const el = ref(null) and access it after onMounted():

el.value.focus();

❓ Can I use ref with child components?

βœ… Yes. You can access public methods of a child component using this.$refs.childName.


❓ What’s the difference between ref() and ref="..."?

βœ… ref="..." is for the template; ref() is for reactive variables in JavaScript.


❓ Should I use refs for communication between components?

βœ… No. Prefer props and $emit() for parent-child communication. Use ref only when necessary.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Vue Template Refs

Or Copy Link

CONTENTS
Scroll to Top