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.
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: '#app', 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: '#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>
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
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 andhas 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.
<div id="app"> <h1 ref="h1Ele">这是H1</h1> <hello ref="ho"></hello> <button @click="getref">获取H1元素</button> </div>
methods: { getref() { // 表示从 $refs对象 中, 获取 ref 属性值为: h1ele DOM元素或组件 console.log(this.$refs.h1Ele.innerText); this.$refs.h1ele.style.color = 'red';// 修改html样式 console.log(this.$refs.ho.msg);// 获取组件数据 console.log(this.$refs.ho.test);// 获取组件的方法 } }
<!-- 列表部分 --> <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?'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="发布日期" 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"></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>
//点击清空条件,调用该方法 emptyAndSearch(){//清空条件方法 //清空树选中状态 this.clearTreeNodeCheck(['tree']); //清除排序 this.$refs.multipleSelection.clearSort(); //设置分页参数 this.queryParam = { startRow : 1, pageSize : 20, condition:{ } } //分页查询调用 this.confirmSearch('statistics'); //设置清空条件为false this.$store.commit('valueDryGoodDatas/SET_CLEAR_ALL',false); }
<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>
//获取元素清除验证 this.$refs.goodPicInfoFormpicUrl.clearValidate()
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!