vue的$refs是什么及怎么使用

這篇文章主要講解了“vue的$refs是什么及怎么使用”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“vue的$refs是什么及怎么使用”吧!

成都創(chuàng)新互聯(lián)公司專注于企業(yè)營銷型網(wǎng)站、網(wǎng)站重做改版、江孜網(wǎng)站定制設(shè)計(jì)、自適應(yīng)品牌網(wǎng)站建設(shè)、H5建站、電子商務(wù)商城網(wǎng)站建設(shè)、集團(tuán)公司官網(wǎng)建設(shè)、成都外貿(mào)網(wǎng)站建設(shè)公司、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計(jì)等建站業(yè)務(wù),價(jià)格優(yōu)惠性價(jià)比高,為江孜等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。

在vue中,$refs是一個對象,持有注冊過ref attribute的所有DOM元素和組件實(shí)例。ref被用來給元素或子組件注冊引用信息,引用信息將會注冊在父組件的“$refs”對象上;如果在普通的DOM元素上使用,引用指向的就是DOM元素;如果用在子組件上,引用就指向組件實(shí)例。

Vue中的$refs

$refs是一個對象,持有注冊過ref attribute的所有DOM元素和組件實(shí)例。

描述

ref被用來給元素或子組件注冊引用信息,引用信息將會注冊在父組件的$refs對象上,

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

  • 如果用在子組件上,引用就指向組件實(shí)例;

另外當(dāng)v-for用于元素或組件的時(shí)候,引用信息將是包含DOM節(jié)點(diǎn)或組件實(shí)例的數(shù)組。

<!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: '#app',
        mounted: function(){
            console.log(this.$refs.node); // <div>Node</div> // DOM元素
            console.log(this.$refs.layout); // VueComponent {_uid: 1, ...} // 組件實(shí)例
            console.log(this.$refs.nodearr); // (3) [div, div, div] // DOM元素?cái)?shù)組
        }
    })
</script>
</html>

因?yàn)閞ef本身是作為渲染結(jié)果被創(chuàng)建的,在初始渲染的時(shí)候是不能訪問的,因?yàn)槠溥€不存在,而且$refs也不是響應(yīng)式的,因此不應(yīng)該試圖用它在模板中做數(shù)據(jù)綁定,在初始化訪問ref時(shí),應(yīng)該在其生命周期的mounted方法中調(diào)用,在數(shù)據(jù)更新之后,應(yīng)該在$nextTick方法中傳遞回調(diào)操作來獲取元素或?qū)嵗送庖话悴煌扑]直接操作DOM元素,盡量使用數(shù)據(jù)綁定讓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: '#app',
        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值) 獲取到的是組件實(shí)例,可以使用組件的所有方法。在使用方法的時(shí)候直接this.$refs.(ref值).方法() 就可以使用了。

3、如何利用 v-for 和 ref 獲取一組數(shù)組或者dom 節(jié)點(diǎn)

應(yīng)注意的坑:

1、如果通過v-for 遍歷想加不同的ref時(shí)記得加 :號,即 :ref =某變量 ;
這點(diǎn)和其他屬性一樣,如果是固定值就不需要加 :號,如果是變量記得加 :號。(加冒號的,說明后面的是一個變量或者表達(dá)式;沒加冒號的后面就是對應(yīng)的字符串常量(String))

2、通過 :ref =某變量 添加ref(即加了:號) ,如果想獲取該ref時(shí)需要加 [0],如this.$refs[refsArrayItem] [0];如果不是:ref =某變量的方式而是 ref =某字符串時(shí)則不需要加,如this.$refs[refsArrayItem]。

vue的$refs是什么及怎么使用

1、ref 需要在dom渲染完成后才會有,在使用的時(shí)候確保dom已經(jīng)渲染完成。比如在生命周期 mounted(){} 鉤子中調(diào)用,或者在 this.$nextTick(()=>{}) 中調(diào)用。

2、如果ref 是循環(huán)出來的,有多個重名,那么ref的值會是一個數(shù)組,此時(shí)要拿到單個的ref 只需要循環(huán)就可以了。

例子1:

添加ref屬性

<div id="app">
    <h2 ref="h2Ele">這是H1</h2>
    <hello ref="ho"></hello>
 
    <button @click="getref">獲取H1元素</button>
</div>

獲取注冊過 ref 的所有組件或元素

methods: {
        getref() {
          // 表示從 $refs對象 中, 獲取 ref 屬性值為: h2ele DOM元素或組件
           console.log(this.$refs.h2Ele.innerText);
           this.$refs.h2ele.style.color = 'red';// 修改html樣式
 
          console.log(this.$refs.ho.msg);// 獲取組件數(shù)據(jù)
          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="標(biāo)題" min-width="80%" sortable="custom">
                        <template slot-scope="scope">
                            <a target="_blank" :class="scope.row.titleClicked?'titleClicked':''" 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="發(fā)布日期" 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('sina',$event);" src="@/images/WEIBO.png">
                                    <img class="hoverHand shareItem" title="分享到微信" @click.stop="shareItem('wx',$event);" src="@/images/WEIXIN.png">
                                    <img class="hoverHand shareItem" title="分享到QQ" @click="shareItem('qq',$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代碼:

//點(diǎn)擊清空條件,調(diào)用該方法
emptyAndSearch(){//清空條件方法
			//清空樹選中狀態(tài)
			this.clearTreeNodeCheck(['tree']);
			//清除排序
			this.$refs.multipleSelection.clearSort();
			//設(shè)置分頁參數(shù)
			this.queryParam = {
				startRow : 1,
                pageSize : 20,
                condition:{
                }
			}
			//分頁查詢調(diào)用
			this.confirmSearch('statistics');
			//設(shè)置清空條件為false
			this.$store.commit('valueDryGoodDatas/SET_CLEAR_ALL',false);
		}

例子3:

Vue代碼:

 <el-form-item
                          ref="goodPicInfoFormpicUrl"
                          :label="$t('許可證證照')"
                          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('查看') }}</el-button>
                        </el-form-item>

JS代碼:

      //獲取元素清除驗(yàn)證
              this.$refs.goodPicInfoFormpicUrl.clearValidate()

一般來講,想獲取INPUT框,首先在獲取DOM元素,需document.querySelector(".input1")獲取這個dom節(jié)點(diǎn),然后在獲取input1的值。

但是用ref綁定之后,我們就不需要在獲取dom節(jié)點(diǎn)了,直接在上面的input上綁定input1,然后$refs里面調(diào)用就行。

然后在javascript里面這樣調(diào)用:this.$refs.input1  這樣就可以減少獲取dom節(jié)點(diǎn)的消耗了。

感謝各位的閱讀,以上就是“vue的$refs是什么及怎么使用”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對vue的$refs是什么及怎么使用這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!

網(wǎng)站欄目:vue的$refs是什么及怎么使用
本文網(wǎng)址:http://bm7419.com/article30/jdieso.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站制作ChatGPT、網(wǎng)站維護(hù)、服務(wù)器托管、微信公眾號、做網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計(jì)公司