This time I will show you how to use $refs in vue, and what are the precautions for using $refs in vue. The following is a practical case, let's take a look.
Generally speaking, to get DOM elements, you need
document<a href="http://www.php.cn/code/658.html" target="_blank">.querySelector(".input1")</a>Get this
dom node, and then get it The value of input1.
But after binding with ref, we no longer need to obtain the dom node. We can directly bind input1 to the above input and then call it in $refs.
Then call this in
javascript: this.$refs.input1 This can reduce the consumption of obtaining dom nodes
The usage is as follows:
HTML:
1 2 3 4 | <p id= "app" >
<input type= "text" ref= "input1" />
<button @click= "add" >添加</button>
</p>
|
Copy after login
JS:
1 2 3 4 5 6 7 8 9 10 | <script>
new Vue({
el: "#app" ,
methods:{
add: function (){
this. $refs .input1.value = "test" ;
}
}
})
</script>
|
Copy after login
The following will introduce the basic usage of vue $refs. The specific code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <p id= "app" >
<input type= "text" ref= "input1" />
<button @click= "add" >添加</button>
</p>
<script>
new Vue({
el: "#app" ,
methods:{
add: function (){
this. $refs .input1.value = "22" ;
}
}
})
</script>
|
Copy after login
General To get the DOM element, you need
document.querySelector(".input1")Get the dom node, and then get the value of input1.
But after binding with ref, we no longer need to obtain the dom node. We can directly bind input1 to the above input and then call it in $refs.
Then call it like this in javascript: this.$refs.input1 This can reduce the consumption of obtaining dom nodes
I believe you have mastered the method after reading the case in this article, please come for more exciting information Pay attention to other related articles on php Chinese website!
Recommended reading:
How to use vue to optimize SMS verification performance
How to implement vue-i18n and vue in vue projects element-ui international development
The above is the detailed content of How to use $refs in vue. For more information, please follow other related articles on the PHP Chinese website!