Vue.js Tutorial
Estimated reading: 4 minutes 31 views

⚙️ Vue.js Template Refs & Lifecycle – Master DOM Access and Component Timing


🧲 Introduction – Get Full Control with Refs, Hooks, and Dependency Injection

In Vue.js, managing component behavior across the app lifecycle is crucial—whether you’re fetching data, manipulating the DOM, or sharing state. Vue provides powerful tools like template refs, lifecycle hooks, and the provide/inject API to give you granular control and seamless component communication.

This section helps you understand how and when to access the DOM, how lifecycle hooks like mounted() work, and how to inject dependencies between components using Vue’s built-in dependency injection system.


🎯 What You’ll Learn:

  • How to access DOM elements and child components using ref
  • How to hook into component lifecycle stages like created, mounted, and destroyed
  • How to use provide and inject for clean dependency sharing between parent and child
  • When to use refs vs. reactive data
  • Best practices for lifecycle-based logic like API calls, event listeners, and timers

📘 Topics Covered

🧩 Topic📌 Description
Vue Template RefsAccess DOM elements or child components using ref
Vue Lifecycle HooksUse hooks like beforeCreate, created, mounted, updated, and destroyed
Vue Provide / InjectShare values and services between parent and child components without props

🔖 Vue Template Refs – Access DOM and Component Instances

Template refs allow you to reference DOM elements or child components directly in your JavaScript logic.

📌 How to Use ref

<template>
  <input ref="inputEl" placeholder="Focus me on mount" />
</template>

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

export default {
  setup() {
    const inputEl = ref(null);

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

    return { inputEl };
  }
}
</script>

✅ Explanation:

  • ref="inputEl" in the template links the DOM element.
  • In setup(), inputEl is defined using Vue’s ref() and accessed via inputEl.value.
  • On the onMounted() hook, we focus the element once it’s in the DOM.

⏱️ Vue Lifecycle Hooks – Manage Behavior Over Time

Lifecycle hooks let you run logic at various points during the component’s life.

📌 Key Lifecycle Hooks in Composition API

import { onBeforeMount, onMounted, onUpdated, onUnmounted } from 'vue';

setup() {
  onBeforeMount(() => console.log('Before mount'));
  onMounted(() => console.log('Mounted'));
  onUpdated(() => console.log('Updated'));
  onUnmounted(() => console.log('Unmounted'));
}

✅ Use Cases:

  • onBeforeMount: setup logic before DOM is rendered.
  • onMounted: fetch data, manipulate DOM, or start timers.
  • onUpdated: respond to DOM updates.
  • onUnmounted: clean up like removing listeners or intervals.

📦 Vue Provide / Inject – Clean State Sharing

Instead of passing props deeply, use provide and inject to share state or methods across component hierarchies.

📌 Provide Example (Parent)

export default {
  setup() {
    provide('theme', 'dark');
  }
}

📌 Inject Example (Child)

export default {
  setup() {
    const theme = inject('theme');
    return { theme };
  }
}

✅ Explanation:

  • provide() sets a key/value pair in the parent.
  • inject() retrieves that value in the child.
  • Useful for global settings, service injection, etc.

🆚 When to Use Refs vs. Reactive Data

Use CaseUse ref()Use reactive()
DOM element access✅ Yes❌ No
Simple reactive primitive✅ Yes (e.g., number, string)❌ Overhead
Reactive object/structure❌ Not ideal✅ Best for objects/arrays
Tracking state✅ For isolated fields✅ For grouped data

📌 Summary – Recap & Next Steps

Mastering refs, lifecycle hooks, and dependency injection in Vue gives you full control over UI behavior and enables clean component communication. These tools are essential for building robust and scalable applications.

🔍 Key Takeaways:

  • Use ref for DOM or component access and reactive for complex state
  • Hook into lifecycle stages like mounted or unmounted to manage async tasks
  • Share services or state without prop drilling using provide/inject

⚙️ Real-World Relevance:
These techniques are crucial in scenarios like forms, modals, dynamic rendering, API handling, and context-aware components.


❓ FAQ – Vue Template Refs & Lifecycle

❓ What is the difference between ref and reactive?

ref is used for primitives and DOM elements; reactive is used for full objects/arrays that need deep reactivity.


❓ Can I use ref to call a method on a child component?

✅ Yes. Assign ref to a child and then call methods using this.$refs.childRef.method() or ref.value.method() in Composition API.


❓ Why is onMounted() preferred for DOM access?

✅ Because DOM elements and child components are only available after mounting—accessing them earlier will return null.


❓ What’s a real use case for provide/inject?

✅ Sharing theme config, auth state, or a global event bus without passing props through every intermediate component.


Share Now :

Leave a Reply

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

Share

Vue Template Refs & Lifecycle

Or Copy Link

CONTENTS
Scroll to Top