首頁  >  文章  >  web前端  >  vue的$refs是什麼意思

vue的$refs是什麼意思

青灯夜游
青灯夜游原創
2022-12-14 19:27:122398瀏覽

在vue中,$refs是一個對象,持有註冊過ref attribute的所有DOM元素和元件實例。 ref被用來給元素或子元件註冊引用訊息,引用訊息將會註冊在父元件的「$refs」物件上;如果在普通的DOM元素上使用,引用指向的就是DOM元素;如果用在子元件上,引用就指向組件實例。

vue的$refs是什麼意思

本教學操作環境:windows7系統、vue3版,DELL G3電腦。

Vue中的$refs

#$refs是一個對象,持有註冊過ref attribute的所有DOM元素和元件實例。

描述

ref被用來給元素或子元件註冊引用訊息,引用訊息將會註冊在父元件的$refs物件上,

  • 如果在普通的DOM元素上使用,引用指向的就是DOM元素;

  • 如果用在子元件上,引用就指向元件實例;

另外當v-for用於元素或元件的時候,引用資訊將是包含DOM節點或元件實例的陣列。 【相關推薦:vuejs影片教學web前端開發

<!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>

因為ref本身是作為渲染結果被創建的,在初始渲染的時候是不能訪問的,因為其還不存在,而且$refs也不是響應式的,因此不應該試圖用它在模板中做數據綁定,在初始化訪問ref時,應該在其生命週期的mounted方法中調用,在數據更新之後,應該在$nextTick方法中傳遞回調操作來取得元素或實例,此外一般不建議直接操作DOM元素,盡量使用資料綁定讓MVVM的ViewModel去操作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>

VUE中$refs的基本用法

ref 有三種用法:

  1 、ref 加在普通的元素上,用this.$refs.(ref值) 取得到的是dom元素

  2、ref 加在子元件上,用 this.$refs.(ref值) 取得到的是元件實例,可以使用元件的所有方法。在使用方法的時候直接this.$refs.(ref值).方法() 就可以使用了。

  3、如何利用v-for 和ref 取得一組陣列或dom 節點

要注意的坑:

1、若透過v-for 遍歷想加上不同的ref時記得加 :號,即 :ref =某變數 ;
這點和其他屬性一樣,如果是固定值就不需要加 :號,如果是變數記得加上 :號。 (加冒號的,表示後面的是變數或表達式;沒加冒號的後面就是對應的字串常數(String))

2、透過 :ref =某個變數 新增ref(即加了:號) ,若想取得該ref時需要加 [0],如this.$refs[refsArrayItem] [0];如果不是:ref =某變數

##的方式而是

 

ref =某字串時則不需要加,例如this.$refs[refsArrayItem]。 1、

ref 需要在dom渲染完成後才會有

,在使用的時候確保dom已經渲染完成。例如在生命週期 mounted(){} 鉤子中呼叫

,或

在this.$nextTick(()=>{}) 中呼叫

2、如果ref 是循環出來的,

有多個重名,那麼ref的值會是一個陣列

 ,此時要拿到單一的ref只需要循環就可以了。

範例1:

新增ref屬性

<div id="app">
    <h1 ref="h1Ele">这是H1</h1>
    <hello ref="ho"></hello>
 
    <button @click="getref">获取H1元素</button>
</div>
取得註冊過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);// 获取组件的方法
        }
      }

範例2:

Vue程式碼:

 <!-- 列表部分 -->
                <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程式碼:###
//点击清空条件,调用该方法
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);
		}
######範例3:#########Vue程式碼: ###
 <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程式碼:###
      //获取元素清除验证
              this.$refs.goodPicInfoFormpicUrl.clearValidate()
###一般來講,想取得INPUT框,先在取得DOM元素,需document.querySelector(".input1")取得這個dom節點,然後在取得input1的值。 ###

但用ref綁定之後,​​我們就不需要在取得dom節點了,直接在上面的input上綁定input1,然後$refs裡面呼叫就行。

然後在javascript裡面這樣呼叫:this.$refs.input1  這樣就可以減少取得dom節點的消耗了

(學習影片分享:vuejs入門教學程式設計基礎影片

以上是vue的$refs是什麼意思的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn