SoFunction
Updated on 2025-04-04

Detailed explanation of the usage and function of $refs in vue

Generally speaking, to obtain the DOM element,(".input1")Get this dom node, and then get the value of input1.

However, after using ref to bind, we don’t need to get the dom node, we can directly bind input1 on the above input, and then call it in $refs.

Then call it in javascript:this.$refs.input1 This will reduce the consumption of obtaining dom nodes

The usage is as follows:

HTML:

<div >
  <input type="text" ref="input1"/>
  <button @click="add">Add to</button>
</div>

JS:

<script>
new Vue({
  el: "#app",
  methods:{
  add:function(){
    this.$refs. ="test"; //this.$refs.input1 Reduce the consumption of obtaining dom nodes    }
  }
})
</script>

Let me introduce the basic usage of vue $refs. The specific code is as follows:

<div >
  <input type="text" ref="input1"/>
  <button @click="add">Add to</button>
</div>

<script>
new Vue({
  el: "#app",
  methods:{
  add:function(){
    this.$refs. ="22"; //this.$refs.input1 Reduce the consumption of obtaining dom nodes    }
  }
})
</script>

Generally speaking, to obtain the DOM element,(".input1")Get this dom node, and then get the value of input1.

However, after using ref to bind, we don’t need to get the dom node, we can directly bind input1 on 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.

Summarize

The above is a detailed explanation of the usage and function of $refs in vue introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message, and the editor will

Reply to everyone in time. Thank you very much for your support for my website!