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

转载于:https://www.cnblogs.com/candy-Yao/p/9210265.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值