Notes on using $refs in Vue instances

Notes on using $refs in Vue instances

During the development process, we often use the instance's vm.$refs(this.$refs) to obtain components registered through ref and perform corresponding operations. However, there are cases where elements cannot be obtained. The root cause is that $refs can only obtain elements after being mounted (rendered).

For example, in this case, it is normal that no node can be obtained if the flag switches from a true value to a false value, because if v-if is a false value, then the node will not be rendered.

However, if you switch from a false value to a true value, you may not be able to get the node. This is because rendering takes time, which can usually be solved using $nextTick().

...
<el-table v-if="flag" ref="table">
  <el-table-column prop="prop1"></el-table-column>
  <el-table-column prop="prop2"></el-table-column>
</el-table>
...
 
 
export default {
  methods: {
    this.$refs.table.XXX()
  }
}

But there is a very special case. When the page is rendered for the first time, $refs cannot get a value. At this time, we need to consider v-show to hide and display component elements.

Because v-show is hidden through CSS display:none, it will be rendered at the beginning and the element will definitely be obtained.

Supplement: Examples and tips for using ref ($refs) in Vue.js

1. Usage summarized according to official documents:

Looking at the ref section in the Vue.js documentation, I summarized the usage of ref for later reference.

1. ref is used on external components

HTML part

<div id="ref-outside-component" v-on:click="consoleRef">
  <component-father ref="outsideComponentRef">
  </component-father>
  <p>ref is on the outer component</p>
</div>

js part

var refoutsidecomponentTem = {
    template:"<div class='childComp'><h5>I am a child component</h5></div>"
  };
  var refoutsidecomponent = new Vue({
    el:"#ref-outside-component",
    components:{
      "component-father":refoutsidecomponentTem
    },
    methods:{
      consoleRef:function () {
        console.log(this); // #ref-outside-component vue instance console.log(this.$refs.outsideComponentRef); // div.childComp vue instance }
    }
  });

2. Ref is used on external elements

HTML Part

<!--ref is on the outer element-->
<div id="ref-outside-dom" v-on:click="consoleRef" >
  <component-father>
  </component-father>
  <p ref="outsideDomRef">ref is on the outside element</p>
</div>

JS part

var refoutsidedomTem = {
    template:"<div class='childComp'><h5>I am a child component</h5></div>"
  };
  var refoutsidedom = new Vue({
    el:"#ref-outside-dom",
    components:{
      "component-father":refoutsidedomTem
    },
    methods:{
      consoleRef:function () {
        console.log(this); // #ref-outside-dom vue example console.log(this.$refs.outsideDomRef); // <p> ref is on the outside element</p>
      }
    }
  });

3. Ref is used on the elements inside --- local registration component

HTML Part

<!--ref on the element inside-->
<div id="ref-inside-dom">
  <component-father>
  </component-father>
  <p>ref is on the element inside</p>
</div>

JS part

  var refinsidedomTem = {
    template:"<div class='childComp' v-on:click='consoleRef'>" +
            "<h5 ref='insideDomRef'>I am a child component</h5>" +
         "</div>",
    methods:{
      consoleRef:function () {
        console.log(this); // div.childComp vue instance console.log(this.$refs.insideDomRef); // <h5 >I am a child component</h5>
      }
    }
  };
  var refinsidedom = new Vue({
    el:"#ref-inside-dom",
    components:{
      "component-father":refinsidedomTem
    }
  });

4. Ref is used on the elements inside --- global registration component

HTML Part

<!--ref on the element inside--global registration-->
<div id="ref-inside-dom-all">
  <ref-inside-dom-quanjv></ref-inside-dom-quanjv>
</div>

JS part

  Vue.component("ref-inside-dom-quanjv",{
    template:"<div class='insideFather'> " +
          "<input type='text' ref='insideDomRefAll' v-on:input='showinsideDomRef'>" +
          " <p>ref on the element inside--globally registered</p> " +
         "</div>",
    methods:{
      showinsideDomRef:function () {
        console.log(this); //This is actually div.insideFather
        console.log(this.$refs.insideDomRefAll); // <input type="text">
      }
    }
  });
  var refinsidedomall = new Vue({
    el:"#ref-inside-dom-all"
  });

2. Pitfalls to watch out for

1. If you want to add different refs through v-for traversal, remember to add the : sign, that is, :ref = a variable;

This is the same as other attributes. If it is a fixed value, you don't need to add a : sign. If it is a variable, remember to add a : sign.

2. Add ref by :ref = a variable (that is, add :). If you want to get the ref, you need to add [0], such as this.$refs[refsArrayItem] [0]. If it is not :ref = a variable but ref = a string, you do not need to add it, such as this.$refs[refsArrayItem]

The difference between adding and not adding [0] - not expanded

The difference between adding and not adding [0] - Expanded

3. When you want to get the DOM after the element ui dialog box is opened, you should use $nextTick instead of directly using this.$refs. imgLocal2:

    console.log('outside this.$refs.imgLocal2', this.$refs.imgLocal2);
    setTimeout(() => {
     console.log('this.$refs.imgLocal2 setTimeout', this.$refs.imgLocal2);
    }, 500); // Not recommended this.$nextTick(() => {
     console.log('this.$refs.imgLocal2 $nextTick', this.$refs.imgLocal2);
    });

The above is my personal experience. I hope it can give you a reference. I also hope that you will support 123WORDPRESS.COM. If there are any mistakes or incomplete considerations, please feel free to correct me.

You may also be interested in:
  • Vue parent component obtains the value and method of child component through $refs
  • Vue basically uses --refs to get instances of components or elements
  • Vue solves the problem of getting DOM or component errors through this.$refs
  • Vue uses refs to get the value process in nested components

<<:  Example of how to set WordPress pseudo-static in Nginx

>>:  What are the new features of Apache Spark 2.4, which will be released in 2018?

Recommend

How to display small icons in the browser title bar of HTML webpage

Just like this effect, the method is also very si...

Examples of new selectors in CSS3

Structural (position) pseudo-class selector (CSS3...

vue3.0+echarts realizes three-dimensional column chart

Preface: Vue3.0 implements echarts three-dimensio...

Div exceeds hidden text and hides the CSS code beyond the div part

Before hiding: After hiding: CSS: Copy code The co...

MySql8 WITH RECURSIVE recursive query parent-child collection method

background When developing a feature similar to c...

Solution to Vue3.0 error Cannot find module'worker_threads'

I'll record my first attempt at vue3.0. When ...

Analyze the method of prometheus+grafana monitoring nginx

Table of contents 1. Download 2. Install nginx an...

JavaScript singleton mode to implement custom pop-up box

This article shares the specific code of JavaScri...

TypeScript decorator definition

Table of contents 1. Concept 1.1 Definition 1.2 D...

How to Fix File System Errors in Linux Using ‘fsck’

Preface The file system is responsible for organi...

Detailed explanation of the 14 common HTTP status codes returned by the server

HTTP Status Codes The status code is composed of ...

Detailed tutorial on running selenium+chromedriver on the server

1. Introduction I want to use selenium to scrape ...

Docker's flexible implementation of building a PHP environment

Use Docker to build a flexible online PHP environ...