Home  >  Article  >  Web Front-end  >  What does $refs in vue mean?

What does $refs in vue mean?

青灯夜游
青灯夜游Original
2022-12-14 19:27:122446browse

In vue, $refs is an object that holds all DOM elements and component instances registered with the ref attribute. ref is used to register reference information for elements or sub-components. The reference information will be registered on the "$refs" object of the parent component; if used on a normal DOM element, the reference points to the DOM element; if used on a sub-component , the reference points to the component instance.

What does $refs in vue mean?

The operating environment of this tutorial: windows7 system, vue3 version, DELL G3 computer.

$refs in Vue

$refs is an object that holds all DOM elements and component instances registered with the ref attribute.

Description

ref is used to register reference information for elements or sub-components. The reference information will be registered on the $refs object of the parent component,

  • If used on a normal DOM element, the reference points to the DOM element;

  • If used on a child component, the reference points to the component instance;

In addition, when v-for is used for elements or components, the reference information will be an array containing DOM nodes or component instances. [Related recommendations: vuejs video tutorial, web front-end development]

<!DOCTYPE html>
<html>
<head>
    <title>Vue</title>
</head>
<body>
    <div id="app">
        <div ref="node">Node</div>
        <layout-div ref="layout"></layout-div>
        <div v-for="i in 3" :key="i" ref="nodearr">{{i}}</div>
    </div>
</body>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
<script type="text/javascript">
    Vue.component("layout-div", {
      data: function(){
          return {
            count: 0
          }
      },
      template: `<div>
                    <div>{{count}}</div>
                </div>`
    })
 
    var vm = new Vue({
        el: &#39;#app&#39;,
        mounted: function(){
            console.log(this.$refs.node); // <div>Node</div> // DOM元素
            console.log(this.$refs.layout); // VueComponent {_uid: 1, ...} // 组件实例
            console.log(this.$refs.nodearr); // (3) [div, div, div] // DOM元素数组
        }
    })
</script>
</html>

Because the ref itself is created as a rendering result, it cannot be accessed during the initial rendering. Because it does not exist yet, and $refs is not responsive, so you should not try to use it for data binding in templates. When initializing access to ref, you should call it in the mounted method of its life cycle. In the data After updating, the callback operation should be passed in the $nextTick method to obtain the element or instance. In addition, it is generally not recommended to directly operate DOM elements. Try to use data binding to let MVVM's ViewModel operate the DOM.

<!DOCTYPE html>
<html>
<head>
    <title>Vue</title>
</head>
<body>
    <div id="app"></div>
</body>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
<script type="text/javascript">
 
    var vm = new Vue({
        el: &#39;#app&#39;,
        data: function(){
            return {
                msg: 0
            }
        },
        template:  `<div>
                       <div ref="node">{{msg}}</div>
                       <button @click="updateMsg">button</button>
                    </div>`,
        beforeMount: function(){
            console.log(this.$refs.node); // undefined
        },
        mounted: function(){
            console.log(this.$refs.node); // <div>0</div>
        },
        methods: {
            updateMsg: function(){
                this.msg = 1;
                console.log(this.$refs.node.innerHTML); // 0
                this.$nextTick(() => {
                    console.log(this.$refs.node.innerHTML); // 1
                })
            }
        }
    })
</script>
</html>

Basic usage of $refs in VUE

ref has three usages:

 1 , ref is added to the ordinary element, use this.$refs. (ref value) What is obtained is the dom element

2. ref is added to the sub-component, use this.$refs. (ref value) What is obtained is the component instance, and all methods of the component can be used . When using the method, you can use it directly this.$refs.(ref value).method().

 3. How to use v-for and ref to obtain a set of arrays or dom nodes

Pits that should be noted:

1. If you want to add a different ref through v-for traversal, remember to add :, that is, :ref = a variable ;
This is the same as other attributes. If it is a fixed value, you do not need to add :. If it is a variable, remember to add :. . (If a colon is added, it means that what follows is a variable or expression; if there is no colon, it means the corresponding string constant (String))

2. Pass :ref = a variable Add ref (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 certain string , there is no need to add it, such as this.$refs[refsArrayItem].

1, ref needs to be after the dom rendering is completed, when using Make sure the dom has been rendered. For example, call in the life cycle mounted(){} hook, or call ## in this.$nextTick(()=>{}) #.

2. If ref is looped out and

has multiple duplicate names, then the value of ref will be an array . At this time, you need to get a single ref Just need to loop.

Example 1:

Add ref attribute

<div id="app">
    <h1 ref="h1Ele">这是H1</h1>
    <hello ref="ho"></hello>
 
    <button @click="getref">获取H1元素</button>
</div>

Get all components or elements registered with ref

methods: {
        getref() {
          // 表示从 $refs对象 中, 获取 ref 属性值为: h1ele DOM元素或组件
           console.log(this.$refs.h1Ele.innerText);
           this.$refs.h1ele.style.color = &#39;red&#39;;// 修改html样式
 
          console.log(this.$refs.ho.msg);// 获取组件数据
          console.log(this.$refs.ho.test);// 获取组件的方法
        }
      }

Example 2:

Vue code:

 <!-- 列表部分 -->
                <el-table @sort-change="sortChange" ref="multipleSelection" border :data="valueDryGoodTableData" style="width: 100%">
                    <el-table-column align="left" prop="title" label="标题" min-width="80%" sortable="custom">
                        <template slot-scope="scope">
                            <a target="_blank" :class="scope.row.titleClicked?&#39;titleClicked&#39;:&#39;&#39;" class="hoverHand bluetext" v-html="scope.row.title" @click="titleClick(scope.row.articleUrl,scope.$index)">
                            </a>
                        </template>
                    </el-table-column>
                    <el-table-column align="left" prop="releaseTime" label="发布日期" min-width="11%" sortable="custom"></el-table-column>
                    <el-table-column align="center" label="操作" min-width="9%">
                        <template slot-scope="scope">
                            <span class="operatoryTools">
                                <i title="取消收藏" v-if="scope.row.isFavour" @click="favoriteOperating(scope.row.id, scope.$index)" class="hoverHand iconStyle el-icon-star-on"></i>
                                <i title="收藏" v-else @click="favoriteOperating(scope.row.id, scope.$index)" class="hoverHand iconStyle el-icon-star-off"></i>
                                <i title="分享" @click.stop="showShareOperation(scope.$index)" class="shareTarg iconfont">&#xe678;</i>
                                <div class="share" v-if="scope.row.showShare">
                                    <img class="hoverHand shareItem" title="分享到微博" @click="shareItem(&#39;sina&#39;,$event);" src="@/images/WEIBO.png">
                                    <img class="hoverHand shareItem" title="分享到微信" @click.stop="shareItem(&#39;wx&#39;,$event);" src="@/images/WEIXIN.png">
                                    <img class="hoverHand shareItem" title="分享到QQ" @click="shareItem(&#39;qq&#39;,$event);" src="@/images/QQ.png">
                                </div>
                                <div v-show="scope.row.erweimaShare" class="erweima_share"></div>
                                <div v-show="scope.row.erweimaShare1" class="erweima_share1"></div>
                            </span>
                        </template>
                    </el-table-column>
                </el-table>

JS code:

//点击清空条件,调用该方法
emptyAndSearch(){//清空条件方法
			//清空树选中状态
			this.clearTreeNodeCheck([&#39;tree&#39;]);
			//清除排序
			this.$refs.multipleSelection.clearSort();
			//设置分页参数
			this.queryParam = {
				startRow : 1,
                pageSize : 20,
                condition:{
                }
			}
			//分页查询调用
			this.confirmSearch(&#39;statistics&#39;);
			//设置清空条件为false
			this.$store.commit(&#39;valueDryGoodDatas/SET_CLEAR_ALL&#39;,false);
		}

Example 3:

Vue code:

 <el-form-item
                          ref="goodPicInfoFormpicUrl"
                          :label="$t(&#39;许可证证照&#39;)"
                          class="is-required"
                          prop="picUrl">
                          <el-upload
                            :show-file-list="false"
                            :http-request="uploadImg"
                            :data="certImgform"
                            action=""
                            class="avatar-uploader">
                            <img
                              v-if="queryFrom.picUrl"
                              :src="queryFrom.picUrl"
                              class="avatar">
                            <i
                              v-else
                              class="el-icon-plus avatar-uploader-icon"/>
                          </el-upload>
                          <el-button
                            type="primary"
                            plain
                            size="mini"
                            @click="viewPcPic(queryFrom.picUrl)">{{ $t(&#39;查看&#39;) }}</el-button>
                        </el-form-item>

JS code:

      //获取元素清除验证
              this.$refs.goodPicInfoFormpicUrl.clearValidate()

Generally speaking, if you want to get the INPUT box, first get the DOM element, you need document.querySelector (".input1") to get the dom node, and then get The value of input1.

But after binding with ref, we no longer need to obtain the dom node. We can directly bind input1 to 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

(Learning video sharing: vuejs introductory tutorial, Basic Programming Video)

The above is the detailed content of What does $refs in vue mean?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn