Vue 获取dom元素之 ref 和 $refs 详解

一、$refs

  一个对象,持有ref注册过的所有元素或子组件。(注册过的 ref 的集合)

二、ref

  被用来给元素或子组件注册引用信息。若用在dom元素上,引用指向的就是dom元素;若用在子组件上,引用指向的是子组件。(引用信息注册在父组件的$refs对象上)

<!-- `vm.$refs.p` will be the DOM node -->
<p ref="p">hello</p>

<!-- `vm.$refs.child` will be the child component instance -->
<child-component ref="child"></child-component>

三、实例

  比如我现在要实现的效果是点击用v-for生成的li ,获取到该元素的值。
  首先要获取当前点击的li元素,我们要做的是:
 
  1、给dom添加点击事件和ref属性。
<li class="sidebar-list"  v-for="(item, index) in meunList"  @click="setPageMenu(index)" ref="menuItem">
    <router-link class="sidebar-a" :to="{ path: item.listLink }" >{{item.listTitle}}</router-link>
</li>

  给组件添加ref属性。

<user-profile ref="profile"></user-profile> 

  2、在点击事件方法中使用ref。

setPageMenu(index) {
//这个是获取当前menuItem值,用index来区分当前元素是v-for 产生的数组中的第几个数
    let getMenuText = this.$refs.menuItem[index].innerText;
}
  访问子组件。
var child = this.$refs.profile  

 

  实例参考地址:https://www.cnblogs.com/xianhuiwang/p/6702712.html

posted @ 2018-06-21 17:48  Candy-Yao  阅读(1173)  评论(0编辑  收藏  举报