Vue进阶(四十):ref ($refs) 用法详解_this


一、前言

ref 有三种用法:

  • ref 作用在普通元素上,用this.ref.name 获取dom元素;
  • ref 作用子组件上,用this.ref.name 获取到组件实例,可以使用组件所有方法。
  • 利用 v-forref 获取一组数据或dom节点
    在这里插入图片描述

二、注意事项

  • ref 需要在dom渲染完成后应用,在使用时确保dom已经渲染完成。比如在生命周期 mounted(){} 钩子中调用,或者在 this.$nextTick(()=>{}) 中调用。
  • 如果ref 是循环出来的,有多个重名,那么ref值会是一个数组 ,此时要拿到单个ref 只需要循环就可以。

三、应用

3.1 ref 作用在外组件
<div id="ref-outside-component" v-on:click="consoleRef">
     <component-father ref="outsideComponentRef">
     </component-father>
     <p>ref在外面的组件上</p>
 </div>
 
 var refoutsidecomponentTem={
     template:"<div class='childComp'><h5>我是子组件</h5></div>"
 };
 var refoutsidecomponent=new Vue({
     el:"#ref-outside-component",
     components:{
         "component-father":refoutsidecomponentTem
     },
     methods:{
         consoleRef:function () {
             console.log(this); // #ref-outside-component     vue实例
             console.log(this.$refs.outsideComponentRef);  // div.childComp vue实例,组件实例
         }
     }
 });

3.2 ref 作用在外元素
<div id="ref-outside-dom" v-on:click="consoleRef" >
   <component-father>
   </component-father>
   <p ref="outsideDomRef">ref在外面的元素上</p>
</div>

var refoutsidedomTem={
    template:"<div class='childComp'><h5>我是子组件</h5></div>"
};
var refoutsidedom=new Vue({
    el:"#ref-outside-dom",
    components:{
        "component-father":refoutsidedomTem
    },
    methods:{
        consoleRef:function () {
            console.log(this); // #ref-outside-dom    vue实例
            console.log(this.$refs.outsideDomRef);  //  <p>标签dom元素 ref在外面的元素上</p>
        }
    }
});

3.3 ref 作用在里面元素上–局部注册组件
<div id="ref-inside-dom">
    <component-father>
    </component-father>
    <p>ref在里面的元素上</p>
</div>

var refinsidedomTem={
    template:"<div class='childComp' v-on:click='consoleRef'>" +
                   "<h5 ref='insideDomRef'>我是子组件</h5>" +
              "</div>",
    methods:{
        consoleRef:function () {
            console.log(this);  // div.childComp   vue实例 
            console.log(this.$refs.insideDomRef);  // <h5 >我是子组件</h5>
        }
    }


### 最后

![前15.PNG](https://img-blog.csdnimg.cn/img_convert/378e89e7348a99684cfc2a37f1b405a2.webp?x-oss-process=image/format,png)

![前16.PNG](https://img-blog.csdnimg.cn/img_convert/0ce1ac536e9e2c9c4e7924df85d872bd.webp?x-oss-process=image/format,png)

>由于文档内容过多,为了避免影响到大家的阅读体验,在此只以截图展示部分内容
>
>**[开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】](https://bbs.csdn.net/topics/618166371)**

为了避免影响到大家的阅读体验,在此只以截图展示部分内容
>
>**[开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】](https://bbs.csdn.net/topics/618166371)**

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值