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? Like
And our vue code is
var vm = new Vue({
el: '#app',
data: {
message: 'Hello CodeCheef!'
},
methods: {
clickedButton: function() {
}
}
});
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.
var vm = new Vue({
el: '#app',
data: {
message: 'Hello CodeCheef!'
},
methods: {
clickedButton: function() {
console.log(this.$refs);
}
}
});
Read also: Vuex Complete Guide with Axios Api Call in Vue Js
Now we can change this button inner text like that:
var vm = new Vue({
el: '#app',
data: {
message: 'Hello CodeCheef!'
},
methods: {
clickedButton: function() {
console.log(this.$refs);
this.$refs.myButton.innerText = this.message;
}
}
});
Let's see another example of vue 3 refs. 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.
#vue-js #vue-3