JAVASCRIPT
Vue 3 Template Refs for Direct DOM Access
Learn how to access DOM elements or component instances directly in Vue 3 using template refs, essential for integrating third-party libraries.
// src/components/DomManipulator.vue
<script setup>
import { ref, onMounted } from 'vue';
// Declare a ref with the same name as the template ref
const myInput = ref(null);
const myDiv = ref(null);
const myComponent = ref(null); // For component instances
onMounted(() => {
// Access the input element's DOM properties
if (myInput.value) {
myInput.value.focus();
myInput.value.style.backgroundColor = '#e0f7fa';
}
// Modify the div's text content
if (myDiv.value) {
myDiv.value.textContent = 'Text changed via ref after mount!';
}
// If 'MyChildComponent' were an actual Vue component,
// myComponent.value would hold its instance.
// Example: if (myComponent.value) myComponent.value.someMethod();
});
const focusInput = () => {
myInput.value?.focus(); // Use optional chaining for safety
};
</script>
<template>
<div>
<p>Input with a ref:</p>
<input ref="myInput" type="text" placeholder="I will be focused" />
<button @click="focusInput">Manual Focus</button>
<p>Div with a ref:</p>
<div ref="myDiv" style="border: 1px solid #ccc; padding: 10px;">
Original text
</div>
<!-- Example of ref on a custom component (assuming MyChildComponent exists) -->
<!-- <MyChildComponent ref="myComponent" /> -->
</div>
</template>
How it works: Template refs in Vue 3 provide a way to directly access DOM elements or child component instances after they are mounted. By declaring a `ref` variable in your script and assigning the same name as the `ref` attribute in your template (e.g., `ref="myInput"`), you can get a direct reference to the underlying element. This is particularly useful for tasks like imperatively focusing an input, integrating with third-party DOM libraries, or calling methods on a child component instance when reactive programming isn't sufficient.