Updated April 11, 2023
Introduction to Vue.js refs
refs in Vue.js is defined as the referencing to make the DOM element selectable by making the key in the parent $refs and considered to be a Vue Instance property. It tells how to directly access the child functions on parent elements using this attribute and they are the most reliable attributes to reach into our templates and grab an element easily meanwhile accessing the data for that element. When a Simple DOM element is used the reference is done with that element. This Special attribute has the beauty to directly access the DOM element to fetch some data.
Syntax:
The general syntax is given as:
<input type ='text' ref= 'name'/>
When we make this in the parent DOM it may expose as this. $refs. input.
How do refs work in Vue.js?
refs is not a standard HTML attributes and it is used only in Vue. When a ref attribute is added to an HTML element through Vue template, then we shall reference that element or in other case taking a child element in the Vue Instance. Generally, it is a read-only attribute and returns an Object. When an element uses ref attribute it automatically creates a link on itself inside this keyword. In other words, when Vue uses refs – say like if it is used for v-for loop, Vue dynamically creates an array of elements and if it is used in a component it refers the component instance. When we use refs in v-for, Vue automatically collects the DOM elements for iterations purpose and store them in an array.
Let’s see how refs work with simple code by accessing the DOM node.
Code:
<template>
<div>
<label for="box">Google: </label>
<input ref="surf" v-model="query" id="box" />
</div>
</template>
<script>
export default {
data: function () {
return {
query: ""
};
},
mounted: function() {
this.$refs["surf"].focus();
}
};
</script>
Above code explains that when we use ref attribute to input element which is accessed inside-mounted with this .$ ref [“surf”].
Examples of Vue.js refs
Given below are the examples of Vue.js refs:
Example #1
Showing simple example on HTML element with refs.
.html
<div id="rrr">
<dem v-ref:ab></dem>
<h3>
{{ $refs.ab.msg }}
</h3>
</div>
.js
var dem = Vue.extend({
name: 'dem',
template: '<p>{{ msg }}</p>',
data: function() {
return { msg: 'Welcome' }
}
})
Vue.component('dem', dem)
var rrr = new Vue({
el: '#rrr'
})
Explanation:
Here the function return the Message by referring <dem> element.
Output:
Example #2
V-ref on V-for Directive
.html
<div id="app">
<h2>Ref attribute v-for does an array</h2>
<ul>
<li v-for="(obj, index) in dataObj" :key="`vfor-${index}`" ref="listItem" class="v-for-li">{{obj.item}}</li>
</ul>
<h2>Ref attribute ternary makes two arrays</h2>
<ul>
<li v-for="(obj, index) in dataObj" :key="`ternary${index}`" :ref="obj.even ? 'expr-1' : 'expr-2'">{{obj.item}}
</li>
</ul>
<h2>Ref attribute function can make multiple arrays*</h2>
<p>List items cannot be Assigned More than two ref</p>
<ul>
<li v-for="(obj, index) in dataObj" :key="`function${index}`" :ref="`${funcRef(index)}`" class="func-item"
:class="`func-${index}`">
{{obj.item}} </li>
</ul>
</div>
.js
new Vue({
el: "#app",
data: {
dataObj: [
{ even: true, item: "apple" },
{ even: false, item: "Mango" },
{ even: true, item: "Pomegranate" },
{ even: false, item: "Guava" },
{ even: true, item: "Cherry" },
{ even: false, item: "Tomato" },
{ even: true, item: "Avacoda" }
]
},
methods: {
funcRef(index) {
return (index % 2 === 0 ) ? 'funcItem-mod-2' :`funcItem-${index}`;
},
addClassToRef(refName, className){
this.$refs[refName].map(el => el.classList.add(className));
}
},
mounted() {
this.addClassToRef('expr-1', 'odd');
this.addClassToRef('expr-2', 'even');
this.addClassToRef('funcItem-mod-2','mod-2');
}
});
Explanation:
Reference Access the data Object through List-items.
Output:
Example #3
Vue refs on handling conditionals
.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>vue-Refs Demo</title>
</head>
<body>
<noscript>
<strong>Hello Welcome .</strong>
</noscript>
<div id="app"></div>
</body>
</html>
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
Test.vue
<template>
<div>
<p v-for="fruits in 5" v-bind:key="fruits" ref="fruits"> List of Fruits {{fruits}}</p>
<button @click="submit">Check to see Refs</button>
</div>
</template>
<script>
export default {
name: 'Test',
data(){
return {
}
},
methods: {
submit(){
console.log(this.$refs)
}
}
}
</script>
<style scoped>
p , input, button{
font-size: 22px;
}
input, button{
font-size: 22px;
}
ul {
list-style-type: none;
padding: 1;
}
li {
display: inline-block;
margin: 0 11px;
}
a {
color: blanchedalmond;
}
</style>
app.vue
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<Test msg="Welcome to Your Vue.js App"/>
</div>
</template>
<script>
import Test from './components/Test.vue'
export default {
name: 'app',
components: {
Test
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: yellowgreen;
margin-top: 50px;
}
</style>
Explanation:
Here in the above code, we use v-for directive so instead of returning objects, refs of array elements return a list of items. When we execute the above code in Visual Code, we get the output like this.
Output:
Example #4
Using input type
App.vue
<template>
<div>
<h2>Refs Example on Counter</h2>
<p>Do Count {{this.counter}} No.of times</p>
<input type="text" ref="input">
<button @click="submit">Increment the Count Each Time</button>
</div>
</template>
<script>
export default {
name: 'Test',
data(){
return {
counter: 1
}
},
methods: {
submit(){
this.counter++;
console.log(this.$refs)
}
}
}
</script>
<style scoped>
p , input, button{
font-size: 18px;
}
input, button{
font-size: 15px;
}
ul {
list-style-type: none;
padding: 1;
}
li {
display: inline-block;
margin: 0 11px;
}
a {
color: blueviolet;
}
</style>
Explanation:
In the above code, we have used a method submit() in which the refs are made to the input and the count value is incremented each time when we input something in the button.
Output:
Conclusion
This article shows how to reference HTML elements – DOM in Vue. All these are done by all the HTML elements properties like child node, attributes. We have also seen how to achieve this various example. Finally, this refs gets famous after the Vue instance has declared and most importantly they directly manipulate Child nodes.
Recommended Articles
This is a guide to Vue.js refs. Here we discuss the introduction, how refs work in Vue.js? along with examples respectively. You may also have a look at the following articles to learn more –