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

当你使用动态绑定的 ref 时,this.$refs

会返回一个数组,而不是直接返回组件实例。因此,你需要通过数组索引来访问具体的组件实例。

示例代码:

bash 复制代码
<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>
相关推荐
老马识途2.0几秒前
在AI的帮助下理解spring的启动过程
java·前端·spring
徐小夕33 分钟前
Loop Engineering 深度解析与实战指南(全网最全)
前端·算法·github
运筹vivo@1 小时前
Python ContextVar 底层机制与内存模型拆解
前端·数据库·python
#麻辣小龙虾#2 小时前
基于vue3.0开发一款【固废与废气运维管理系统】(支持源码)
前端·vue.js·vue3
Cosolar2 小时前
Docsify零构建文档站完全指南:从快速搭建到企业级部署
前端·开源·github
weixin_471383032 小时前
Taro-02-页面路由
前端·taro
星栈独行2 小时前
Makepad 应用如何读文件、调接口、保存数据
前端·程序人生·ui·rust·github
一 乐3 小时前
家政服务管理系统|基于springboot + vue家政服务管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·家政服务管理系统
IT_陈寒3 小时前
Vite热更新失效?可能你在用Windows
前端·人工智能·后端
烬羽4 小时前
后端返回的 JSON 字符串,浏览器怎么"看懂"的?——Ajax 全链路拆解
javascript