What is $refs and ref

Let’s take a look at what the official document says about them:

  1. First of all, what is a ref

Ref is used to register reference information for an element or child component. The reference information will be registered with the parent component’s $refs object. If used on a normal DOM element, the reference refers to the DOM element. If used on a child component, the reference refers to the component instance.

  1. What is $refs

An object that holds all DOM elements and component instances registered with ref Attributes.

$refs = ref (); $refs = ref (); As I get to it, let’s test our results, and in the process maybe we’ll get a sense of what they’re doing.

Ref registers reference information for the element

First, the code:

<div id="demo">
  <p ref="refDemo"></p>
</div>
Copy the code
var vm=new Vue({
   el:'#demo'
})
Copy the code

We can see that when we register a reference to an element we need to give it a String value. What’s the use of this value? Naturally for the $refs call, let’s try it out.

console.log(vm.$refs.refDemo)
Copy the code

So let’s print it out and see what this is.

As mentioned in the API, when a ref registers an element, it points to the element itself.

Ref Registers reference information for the component

As usual, the above example code:

<div id="demo">
  <child ref="component"></child> 
</div>
Copy the code
   Vue.component('child', {template:`<p></p>`.methods: {
       sayHi(){
         console.log('I'm a child component')}},})var vm=new Vue({
     el:'#demo',})console.log(vm.$refs.component)
Copy the code

We registered a global component child in the instance and referenced it in the div. Here we also print what this reference refers to. As follows:

And you can see that he’s doing a lot more output than that, so obviously this ischildComponent instance, the method we registered on the componentsayHiAs you can also see in the output, it’s a good idea to register a reference to a component using ref when we need to call a child component’s method directly or get a value.