Vue3 Ref Component

Posted on  by admin
Hello vue devs in this example i am going to discuss about vue 3 refs example with many example with source code so that you can understand better.

This template refs is only available in vue 3 version. So you will learn from this tutorial about vue refs details.

You can ask that why vue refs? What is the purpose of using this? Ok, let me clear about all of those questions. From the vue 3 official docs we can say that despite the existence of props and events, sometimes you might still need to directly access a child component in JavaScript.

To attain it we can assign a reference ID to the child component or HTML element using the ref attribute.

For example what we did before?

And our vue code is. But what if we add refs in html element?

Look adding a ref attribute to any html element within the template, we can refer to these elements on Vue instance.

More clearly, we can access the DOM elements. So let’s try it out on that button that I have added in above and make it for refs to use.

Look you have seen that the button already has a click event handler which doesn’t do anything yet. Note :The ref attribute is not a standard HTML attribute, so it is only used by Vue.

Now we can reference this button by using the ref name myButton.

We can do this by using the $refs property on you Vue instance. Let’s log this to the console and see what it looks like, you can clearly see everything related to its property. Read also: Vuex Complete Guide with Axios Api Call in Vue Js.

Now we can change this button inner text like that:.
DylanDylan
8,615
1

WARNING : $refs property are only populated after the component has been rendered. Hope it can help you. In my previous post, I implemented my first Vue3 component. I implementend a very simple web app (roll the dice) where I had a “div” where to show the result and a button to trigger the roll and generate a random number from 1 to 6.

In that case, I used “ref()” to create reactive properties.

“My first Vue3 component” article where I used ref() for declaring reactive properties: https://medium.com/swlh/my-first-vue3-component-6e1ef1670544. For example in “setup()” function of my component I declared “dice” property in order to store the last result of the roll action. The “dice” property was an integer, initialized with 0.

To make it reactive, I used “ref()” function to initialize it.

So “dice” it was not just a simple integer but an object:. In this way “dice” is a object with “value” attribute. This means that, if you want to access to the “dice” value in your component, you need to use “dice.value”.

Looking for a Vue.js job?

Another way to make the properties reactive is to use “reactive()” function.

The first difference from developer perspective is that using “ref()” you need to declare each single property.

and when you send the properties to the template you need to list them individually:.

Static $refs