JAVASCRIPT
Accessing DOM Elements and Components with Template Refs in Vue 3
Discover how to use `ref` as a template ref in Vue 3 to directly access DOM elements or component instances, enabling fine-grained control and third-party library integrations.
<template>
<div>
<h1>Template Refs Example</h1>
<!-- Ref for a DOM element -->
<input type="text" ref="myInput" placeholder="Focus me on mount" />
<button @click="focusInput">Focus Input</button>
<!-- Ref for a component instance -->
<ChildComponent ref="childComp" />
<button @click="callChildMethod">Call Child Method</button>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
// Define refs
const myInput = ref(null);
const childComp = ref(null);
// Focus the input when the component is mounted
onMounted(() => {
if (myInput.value) {
myInput.value.focus();
console.log('Input focused automatically!');
}
});
const focusInput = () => {
if (myInput.value) {
myInput.value.focus();
}
};
const callChildMethod = () => {
if (childComp.value) {
// Assuming ChildComponent has a method called 'greet'
childComp.value.greet('from parent!');
}
};
// Define a simple child component for demonstration
const ChildComponent = {
template: `
<div style="border: 1px solid blue; padding: 10px; margin-top: 10px;">
<h3>Child Component</h3>
<p>Message: {{ childMessage }}</p>
<button @click="greet('from child button')">Say Hello</button>
</div>
`,
setup() {
const childMessage = ref('Hello from child!');
const greet = (msg) => {
alert(`Child says: ${childMessage.value} ${msg}`);
};
// Expose the greet method so parent can call it
return {
childMessage,
greet
};
}
};
</script>
How it works: This snippet demonstrates the use of template refs (`ref` with `ref` attribute) in Vue 3 to gain direct access to DOM elements or child component instances. By declaring a ref (`myInput = ref(null)`) and attaching it to an element (`ref="myInput"`), you can access the underlying DOM node via `myInput.value` after the component mounts. Similarly, attaching a ref to a child component allows you to call its exposed methods (via `defineExpose` if using `<script setup>`, or simply by returning methods from setup). This is vital for integrating third-party libraries that require direct DOM manipulation or for specific component interactions.