vue2中ref的正确用法

ref
是什么

ref:被用来给元素或子组件注册引用信息,引用信息将会注册在父组件的$refs对象上。如果在普通的DOM元素上使用,那么指向的就是普通的DOM元素。

如何使用
  1. ref 加在普通的元素上 ,使用this.$refs.name 获取注册的元素
<div id="app7">
  <input type="text"ref="myInput"/ >
  <button @click="showRef">show</button>
</div>
var fatComp=new Vue({
  el:"#fatComp",
  data:{
 
  },
  methods:{
    showRef:function(){
      console.log(this.$refs.myInput)
      console.log(this.$refs);
    }
  }
})

输出的结果是:
<input data-v-0fe792bb="" type="text">
{TEXT: input}
  1. ref 加在子组件上,用this.ref.name 获取到的是组件实例,可以使用组件的所有方法。
<div id="app7">
  <childComp ref=inputText></childComp>
  <button @click="add">show</button>
</div>
Vue.component('childComp',{
   template:"<div>我是一个组件</div>"
 })
 var fatComp=new Vue({
   el:"#fatComp",
   data:{
 
   },
   methods:{
     add:function(){
       console.log(this.$refs.inputText);
       console.log(this.$refs);
     }
   }
 })
 var aaa=fatComp.$refs.inputText;



  1. ref和v-for在一起的情况
<template>
  <div class="hello">
    <div v-for="item in  5" :key="item">
      <span :ref="'item'+item">{{item}}</span>
    </div>
    <button @click="showRef">show</button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String
  },
  mounted() {
    console.log("11111111111==============");
    this.$nextTick(() => {
      console.log(this.$refs.item1[0]);
      //<span data-v-469af010="">1</span>
      console.log(this.$refs.item1);
      // [span];
      console.log(this.$refs);
      //item1: [span]
      // item2: [span]
      // item3: [span]
      // item4: [span]
      // item5: [span]
    });
  },
  methods: {
    show() {
      console.log(this.a);
    },
    showRef() {
      console.log(this.$refs.item1);
      console.log(this.$refs);
    }
  }
};
</script>

<style scoped>

</style>

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值