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.
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.
Wrapping it up
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.
Looking for a Vue.js job?
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:. Let's see another example of vue 3 refs.
Dynamic $refs in v-for
Using Vue's ref we can easily read files from < input >. By specifying input type to file and giving the < input > tag a ref property along with a ref name,.
WARNING : $refs property are only populated after the component has been rendered. Hope it can help you. You've seen in the last tip "Use old instance properties in Composition API in Vue.js 3" how to access instance properties in the new syntax.
However, our beloved this.$refs wasn't included in the setup context object as you realized if you read the tip.
1. What is the problem when I use reactive() to deal with array?
So, how can you work with template refs in Composition API?
It might be more simple than you think! The thing is, Vue.js unifies the concept of refs, meaning that you just need to use the ref() function you already know for declaring reactive state variables in order to declare a template ref as well.
Only keep in mind that the ref name must be the same as the variable's one.
Let me illustrate it. For the template:. I've set titleRef on the
tag. That's all in the template level. Now in the setup function, you need to declare a ref with the same titleRef name, initialized to null for instance:.
You access the ref value just like any other reactive ref, by accessing the .value property. If you do so as shown in the example you should see in the console the result titleRef .