JAVASCRIPT
Direct DOM Access in Vue 3 with Template Refs
Discover how to access and manipulate specific DOM elements directly within your Vue 3 components using template refs, essential for integrating with third-party libraries.
<template>
<div>
<input ref="myInput" type="text" placeholder="Focus me on mount" />
<button @click="focusInput">Focus Input</button>
<p ref="myParagraph">This is a paragraph.</p>
<button @click="changeParagraphColor">Change Paragraph Color</button>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
// Create a ref for the input element
const myInput = ref(null);
// Create a ref for the paragraph element
const myParagraph = ref(null);
onMounted(() => {
// Access the input element once the component is mounted
// myInput.value will be the actual DOM element
if (myInput.value) {
myInput.value.focus();
}
});
const focusInput = () => {
if (myInput.value) {
myInput.value.focus();
}
};
const changeParagraphColor = () => {
if (myParagraph.value) {
myParagraph.value.style.color = 'blue';
myParagraph.value.style.fontWeight = 'bold';
}
};
</script>
How it works: This snippet demonstrates the use of template refs in Vue 3 to directly access DOM elements. By assigning a `ref` attribute to an HTML element (e.g., `<input ref="myInput">`), you can then access that element's DOM node in your script using `myInput.value`. This is particularly useful for tasks that require direct DOM manipulation, such as focusing an input field on component mount, measuring element dimensions, or integrating with non-Vue third-party JavaScript libraries.