JAVASCRIPT

Direct DOM Access and Component Methods with Template Refs in Vue 3

Discover how to use the 'ref' attribute and `ref()` in Vue 3's Composition API to directly access DOM elements or child component instances for imperative operations.

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

// Template ref for a DOM element
const myInput = ref(null);

// Template ref for a child component
const childComponentRef = ref(null);

// Child component definition
const ChildComponent = {
  template: '<div>Child Component: {{ childMessage }} <button @click="greetChild">Say Hello</button></div>',
  data() { return { childMessage: 'I am a child.' }; },
  methods: {
    focusAndHighlight() {
      console.log('Child component method called: Focusing and Highlighting');
      this.childMessage = 'I am focused!';
      // In a real scenario, you might interact with a child's internal DOM here
    },
    greetChild() {
      alert('Hello from child!');
    }
  }
};

onMounted(() => {
  // Accessing DOM element and performing an action
  if (myInput.value) {
    myInput.value.focus();
    myInput.value.style.backgroundColor = '#f0f0f0';
  }

  // Accessing child component instance and calling its method
  if (childComponentRef.value) {
    childComponentRef.value.focusAndHighlight();
  }
});

const manuallyFocusInput = () => {
  if (myInput.value) {
    myInput.value.focus();
  }
};
</script>

<template>
  <div>
    <h3>DOM Element Access</h3>
    <input type="text" ref="myInput" placeholder="I will be focused on mount" />
    <button @click="manuallyFocusInput">Manually Focus Input</button>

    <h3>Child Component Access</h3>
    <ChildComponent ref="childComponentRef" />
  </div>
</template>
How it works: This example illustrates the use of template refs (`ref="myInput"`) to gain direct access to DOM elements or child component instances within a Vue 3 component. The `ref()` function in the script creates a reactive reference that initially holds `null` and gets populated with the actual element or component instance after the component is mounted. This allows imperative actions like focusing an input or calling a child component's method.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs