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>
相关推荐
AI视觉网奇6 分钟前
Uncaught SyntaxError: Failed to construct ‘RTCPeerConnection‘:
前端·javascript·html
再学一点就睡7 小时前
前端网络实战手册:15个高频工作场景全解析
前端·网络协议
C_心欲无痕8 小时前
有限状态机在前端中的应用
前端·状态模式
C_心欲无痕8 小时前
前端基于 IntersectionObserver 更流畅的懒加载实现
前端
candyTong8 小时前
深入解析:AI 智能体(Agent)是如何解决问题的?
前端·agent·ai编程
柳杉8 小时前
建议收藏 | 2026年AI工具封神榜:从Sora到混元3D,生产力彻底爆发
前端·人工智能·后端
weixin_462446238 小时前
使用 Puppeteer 设置 Cookies 并实现自动化分页操作:前端实战教程
运维·前端·自动化
CheungChunChiu8 小时前
Linux 内核动态打印机制详解
android·linux·服务器·前端·ubuntu
Irene19919 小时前
Vue 官方推荐:kebab-case(短横线命名法)
javascript·vue.js
GIS之路9 小时前
GDAL 创建矢量图层的两种方式
前端