JAVASCRIPT

Accessing DOM Elements Programmatically with Template Refs

Learn how to use `ref` in Vue 3 to directly access a DOM element or child component instance in your templates for programmatic manipulation.

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

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

// Declare a ref for a child component instance (assuming ChildComponent exists)
// const childComponentRef = ref(null);

onMounted(() => {
  // Access the DOM element after it's mounted
  if (myInput.value) {
    myInput.value.focus();
    console.log('Input focused programmatically.');
  }

  if (myDiv.value) {
    myDiv.value.style.backgroundColor = '#e0f7fa';
    console.log('Div background color changed.');
  }

  // If you had a child component ref:
  // if (childComponentRef.value) {
  //   childComponentRef.value.someMethod(); // Call a method on the child component
  // }
});

const setInputValue = () => {
  if (myInput.value) {
    myInput.value.value = 'Hello Vue!';
  }
};
</script>

<template>
  <div>
    <h1>Template Refs Example</h1>
    <input type="text" ref="myInput" placeholder="I will be focused" />
    <button @click="setInputValue">Set Input Value</button>
    <div ref="myDiv" style="padding: 20px; border: 1px solid #ccc; margin-top: 10px;">
      This div's background will change.
    </div>
  </div>
</template>
How it works: Template refs in Vue 3 provide a way to gain direct access to a DOM element or a child component instance after it has been mounted. By declaring a `ref` and binding it to an element with `ref="refName"`, you can then access that element's properties and methods programmatically within your script, typically in `onMounted`. This is useful for tasks like focusing inputs, triggering animations, or interacting with third-party libraries that require direct DOM manipulation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs