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 count the number of specific characters in a file in Linux

Counting the number of a string in a file is actu...

JavaScript to implement limited time flash sale function

This article shares the specific code of JavaScri...

A brief discussion on the types of node.js middleware

Table of contents Overview 1. Application-level m...

HTML web page image tag

Insert image tag <IMG> The colorful web page...

Vue implements multi-grid input box on mobile terminal

Recently, the company has put forward a requireme...

translate(-50%,-50%) in CSS achieves horizontal and vertical centering effect

translate(-50%,-50%) attributes: Move it up and l...

How to modify port 3389 of Windows server 2008 R2 remote desktop

The default port number of the Windows server rem...

Tutorial on installing phpMyAdmin under Linux centos7

yum install httpd php mariadb-server –y Record so...

Detailed tutorial on uploading and configuring jdk and tomcat on linux

Preparation 1. Start the virtual machine 2. git t...

Summary of some common techniques in front-end development

1. How to display the date on the right in the art...

Detailed explanation of the error problem of case when statement

Preface In the MySQL database, sometimes we use j...

A brief analysis of MySQL cardinality statistics

1. What is the cardinality? Cardinality refers to...

Vue elementUI implements tree structure table and lazy loading

Table of contents 1. Achieve results 2. Backend i...