Introduction
There are situations where we tend to have direct access to a child component in javascript even after having props and events. We can easily assign a reference ID to the HTML element or the child component that uses the ref attribute to gain this.
Let’s understand this with an example:
| <input ref="input" /> |
Implementation
This can come in handy when we want to focus this input on our component mount programmatically and now let’s have a look at the code as well:
|
const app = Vue.createApp({})
app.component('base-input', { template: ` <input ref="input" /> `, methods: { focusInput() { this.$refs.input.focus() } }, mounted() { this.focusInput() } }) |
We can also add ref to the component directly, and we can use it to trigger focus input events from our parent component easily.
Let's have a quick look on the both the Html and Javascript code:
Html
| <base-input ref="usernameInput"></base-input> |
JavaScript
| this.$refs.usernameInput.focusInput() |
And now this sums up the Template Refs in VueJs.
Let's have a quick look at the frequently asked questions too.
Frequently Asked Questions
-
Where do we use template refs?
Ans: there are situations where we tend to have direct access to a child component in javascript even after having props and events. We can easily assign a reference ID to the HTML element or the child component that uses the ref attribute to gain this.
-
How can we implement template refs?
Ans: This can come in handy when we focus this input on programmatically component mounts. We can also add ref to the component directly, and we can use it to trigger focus input events from our parent component easily.
-
Is Vue faster than React?
Ans: Vue is faster than react in complex applications. However, React is more closed for other applications.




