While Vue's declarative rendering abstracts away most direct DOM manipulations, sometimes you need direct access.
You might need to manually focus an input field, trigger a complex animation, or integrate a third-party library.
To safely access the underlying DOM elements, Vue provides a feature called "Template Refs".
To create a reference to a DOM element, you use the special ref attribute.
You attach this attribute directly to the HTML tag you want to access.
Vue will then expose this specific element to your JavaScript component logic.
<!-- Attaching a ref to a standard input --> <input ref="myInput" type="text" placeholder="I will be focused!">
If you are using the traditional Options API, all refs are stored inside the this.$refs object.
You can access your element by calling this.$refs.myInput.
This grants you full access to standard vanilla JavaScript DOM methods, like .focus().
export default {
mounted() {
// Focuses the input immediately when the component loads
this.$refs.myInput.focus();
}
}
If you are using the modern <script setup> syntax, accessing refs works slightly differently.
You must declare a reactive ref() variable with the exact same name as your template attribute.
Vue will automatically connect the DOM element to your newly declared variable!
<script setup>
import { ref, onMounted } from 'vue'
// Must match the ref="myInput" in the template exactly
const myInput = ref(null)
onMounted(() => {
myInput.value.focus()
})
</script>
What is the primary purpose of the 'ref' attribute in Vue?
In the Options API, which object stores all the template references?