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>
相关推荐
程序员的世界你不懂1 小时前
【Flask】测试平台开发,重构提测管理页面-第二十篇
vue.js·重构·flask
IT_陈寒1 小时前
Python异步编程的7个致命误区:90%开发者踩过的坑及高效解决方案
前端·人工智能·后端
猫猫村晨总1 小时前
整理了几道前端面试题
前端·vue.js·面试
江拥羡橙1 小时前
【目录-多选】鸿蒙HarmonyOS开发者基础
前端·ui·华为·typescript·harmonyos
你的电影很有趣1 小时前
lesson55:CSS导航组件全攻略:从基础导航条到动态三级菜单与伸缩菜单实现
前端·css
蔗理苦1 小时前
2025-09-05 CSS4——浮动与定位
开发语言·前端·css·html·css3
浊浪载清辉2 小时前
《Html泛型魔法学院:用霍格沃茨风格网页教授集合框架》
前端·javascript·学习·html
Want5952 小时前
HTML元素周期表
前端·html
一只一只妖5 小时前
突发奇想,还未实践,在Vben5的Antd模式下,将表单从「JS 配置化」改写成「模板可视化」形式(豆包版)
前端·javascript·vue.js
悟能不能悟8 小时前
js闭包问题
开发语言·前端·javascript