JAVASCRIPT
Access DOM Elements with Template Refs in Vue 3
Learn how to access specific DOM elements or child component instances directly in Vue 3 using template refs (`ref()` and `ref='myElement'`) and the `onMounted` lifecycle hook for imperative interactions.
// src/components/DomManipulator.vue
<template>
<div>
<input ref="myInput" type="text" placeholder="Focus me on load" />
<p ref="myParagraph">This is a paragraph.</p>
<button @click="logElementContent">Log Paragraph Content</button>
<ChildComponent ref="childCompRef" />
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import ChildComponent from './ChildComponent.vue'; // Assume this exists
// Declare refs for DOM elements and child components
const myInput = ref(null);
const myParagraph = ref(null);
const childCompRef = ref(null);
onMounted(() => {
// Accessing and manipulating the input element
if (myInput.value) {
myInput.value.focus(); // Focus the input field on component mount
myInput.value.value = 'Hello Vue!';
}
// Accessing and manipulating the paragraph element
if (myParagraph.value) {
console.log('Paragraph content on mount:', myParagraph.value.textContent);
myParagraph.value.style.color = 'blue';
}
// Accessing a child component instance (if it exposes methods/properties)
if (childCompRef.value) {
console.log('Child component instance:', childCompRef.value);
// If ChildComponent had an exposed method like `childMethod`
// childCompRef.value.childMethod();
}
});
const logElementContent = () => {
if (myParagraph.value) {
alert(`Paragraph content: ${myParagraph.value.textContent}`);
}
};
</script>
// src/components/ChildComponent.vue (for context)
/*
<template>
<div>
<h3>I am a Child Component</h3>
<p>My internal state: {{ message }}</p>
</div>
</template>
<script setup>
import { ref, defineExpose } from 'vue';
const message = ref('Hello from child!');
// Expose properties/methods if parent needs to access them
defineExpose({
message,
childMethod: () => console.log('Child method called!')
});
</script>
*/
How it works: This snippet demonstrates how to directly access DOM elements or child component instances in Vue 3 using template `ref` attributes and the `ref()` API from the Composition API. By assigning a `ref` to an element in the template (e.g., `ref='myInput'`) and declaring a corresponding `ref` variable in the script setup, you can access the underlying DOM node or component instance within the `onMounted` hook or other imperative logic. This is crucial for tasks like focusing input fields, integrating with third-party libraries that require direct DOM manipulation, or calling methods on child components.