In Vue, template refs allow us to reference and manipulate DOM elements or components directly within our template.
They provide a way to access elements in the template directly without needing to query the DOM manually using Javascript.
This is particularly useful when we need to interact with elements imperatively, such as focusing an input, accessing properties or methods of a child component, or attaching event listeners directly to DOM elements.
Accessing DOM Elements: When we need to manipulate or access properties of DOM elements directly, such as focusing an input field, triggering animations, or measuring element dimensions, for that we can use Ref in our Components.
Accessing Child Components: When we want to call methods, access properties, or manipulate the state of child components from the parent component.
<template> <input type="text" ref="inputFieldRef" > <button @click="focusInputField" > Focus Input Field </button> </template> <script> export default { methods: { focusInputField() { // Accessing the input element using the $refs property this.$refs.inputFieldRef.focus(); } } }; </script>
the ref="inputFieldRef" attribute is added to the input field element.
This allows us to reference the input element using "this.$refs.inputFieldRef" in the component's methods.
when we click on the "Focus Input Field" Button `the focusInputField` function will invoked and with the help of the `$refs` property it will get direct access to the input field element and focus the input field element using the "focus()" method.
<template> <ChildComponent ref="childComponentRef"></ChildComponent> <button @click="focusChildInputField" > Focus Child Input Field </button> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { focusChildInputField() { // Accessing the child component instance using the $refs property this.$refs.childComponentRef.childMethod(); } } }; </script>
the ref="childComponentRef" attribute is added to the `ChildComponent`.
This allows us to reference the child component using "this.$refs.childComponentRef" in the component's methods.
<template> <input ref="childComponentRef" /> </template> <script> export default { methods: { childMethod() { // Accessing the child component instance using the $refs property this.$refs.childComponentRef.focus(); }, }, }; </script>
When the "Focus Child Input Field" button is clicked from the Parent Component, the "focusChildInputField" method gets invoked, which calls a method `childMethod()` defined in the child component.
Template refs are particularly useful for accessing DOM elements or child components directly within our template, especially when we need to perform imperative operations on them.
However, it's important to use template "refs" judiciously and be aware of the potential limitations, such as the loss of reactivity when directly manipulating the DOM.