Template Refs in VueJs

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

  1. 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.
     
  2. 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.
     
  3. Is Vue faster than React?
    Ans: Vue is faster than react in complex applications. However, React is more closed for other applications.

Key Takeaways

Hey everyone, so let's brief about the article where we have described what template refs in venues are:

  • This article has explained what template refs in vueJs are. 
  • We have further discussed how to implement template refs. 
  • Additionally, we have seen the Html and the Javascript code for them and how we can implement them.


Isn’t Web Development engaging? Building new websites and using amazing animations and different APIs, don’t be scared if you cannot grasp the hold of this vast development. We have the perfect web development course for you to make you stand out from your fellow developers. 

Happy Learning Ninjas!

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think