vue中动态绑定ref后,获取某个具体组件实例

当你使用动态绑定的 ref 时,this.$refs
会返回一个数组,而不是直接返回组件实例。因此,你需要通过数组索引来访问具体的组件实例。

示例代码:

<template>
  <div>
    <!-- 动态绑定 ref(v-for 循环场景) -->
    <div v-for="(item, index) in items" :key="index">
      <input 
        :ref="el => { setItemRef(el, index) }" 
        v-model="item.value"
        @blur="handleBlur(index)"
      >
    </div>

    <button @click="showRefs">查看所有 refs</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { value: '第一个输入框' },
        { value: '第二个输入框' },
        { value: '第三个输入框' }
      ],
      // 存储动态 ref 的数组
      inputRefs: []
    }
  },
  methods: {
    // 动态设置 ref 的回调函数
    setItemRef(el, index) {
      if (el) {
        this.inputRefs[index] = el
      }
    },
    // 通过索引访问具体实例
    handleBlur(index) {
      const currentInput = this.inputRefs[index]
      console.log('失去焦点的输入框:', currentInput.value)
    },
    showRefs() {
      // 两种访问方式:
      // 方式1:通过我们自己维护的数组
      console.log('自定义数组:', this.inputRefs) 

      // 方式2:通过官方 $refs(需注意是数组)
      console.log('$refs 数组:', this.$refs.dynamicInput)
      console.log('第一个输入框实例:', this.$refs.dynamicInput)
    }
  }
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值