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

Generally speaking, to get the DOM element, you need to use the document.querySelector('#input1') method to get the dom node, and then get the value of input1.

But after using ref binding, we don't need to get the dom node anymore, we can directly bind input1 to the above input, and then call it in $refs.

In JavaScript, it is called through this.$refs.input1. This approach actually accesses the DOM virtualized by VUE, which can effectively reduce the performance consumption of acquiring/operating DOM nodes.

HTML

<div id="app">
  <input type="text" ref="input1" />
  <button @click="add">添加</button>
</div>

JavaScript

new View({
  el: "#app",
  methods:{
  add: function (){
     this .$refs.input1.value = "test"; // Effectively reduce the performance consumption of obtaining dom nodes 
    }
  }
})

The $refs here can be regarded as a selector for ref. This $ref is an object, and the object stored in it can be obtained through the key.

Of course, since it is an object, it can also be accessed using the square bracket operator, specifically this.$refs[input1].

 

"I'm just afraid I'll never see you again."

Reprinted in: https://www.cnblogs.com/yanggb/p/11536282.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324843984&siteId=291194637