Vue3 动态设置 ref

el-tabs中如果用 v-for动态增加tab,每个tab中如果需要控制自己控件的增删改查,就需要设置动态ref.

  1. 先定义一个空字典:
TypeScript 复制代码
const inputRefMap = ref({});
  1. 然后定义一个方法将变量增加到字典中:
TypeScript 复制代码
const handleSetInputMap = (el: refItem, item: number) => {
  if (el) {
    inputRefMap.value[`Input_Ref_${item}`] = el;
  }
};
  1. template中调用该方法:
TypeScript 复制代码
:ref="(el:refItem) => handleSetInputMap(el, item.Id)"
  1. 使用该变量:
TypeScript 复制代码
const addClick = (item: number) => {
  inputRefMap.value[`Input_Ref_${item}`].addRow();
};

全部代码参考如下:

TypeScript 复制代码
<script setup lang="ts">
import { ComponentPublicInstance } from "vue";
const inputRefMap = ref({});
const listInfo = ref<Array<any>>();
type refItem = Element | ComponentPublicInstance | null;
const handleSetInputMap = (el: refItem, item: number) => {
  if (el) {
    inputRefMap.value[`Input_Ref_${item}`] = el;
  }
};

const addClick = (item: number) => {
  // 调用该控件下的方法 .addRow()
  inputRefMap.value[`Input_Ref_${item}`].addRow();
};
</script>



<template>
  <el-tabs type="border-card">
    <el-tab-pane
      v-for="(item, index) in listInfo"
      :key="index"
      :label="item.EquipName"
    >
      <PartDivider title="竞对中标结果更新" v-if="item.Competitors.length">
        <template #handle>
          <el-button
            type="primary"
            size="small"
            v-if="editStatus"
            @click="addClick(item.Id)"
            link
            >新增</el-button
          >
        </template>
        <bidCompetitorResultList
          :ref="(el:refItem) => handleSetInputMap(el, item.Id)"
          :FormSn="item.FormSn"
          :competitorList="item.Competitors"
          :BidResultsList="BidResults"
          :editStatus="editStatus"
          :currencyType="CurrencyShort(item.Currency)"
        />
      </PartDivider>
    </el-tab-pane>
  </el-tabs>
</template>
相关推荐
心运软件8 小时前
SpringBoot+ Vue校园社团管理平台的完整架构设计
vue.js·后端
sunly_9 小时前
React useActionState 的用法详解
前端·javascript·react.js
cyadyx10 小时前
【Three.js】Three.js 中加载 3D 模型
前端·javascript·3d
汉堡大王952710 小时前
前端工程师 TypeScript 上手指南:一条清晰的从入门到精通路线
前端·javascript·react.js
wear工程师10 小时前
防抖为什么会失效?React 面试里的闭包和定时器
javascript·react.js
浅水壁虎10 小时前
vue基础(第四章 Pinia)
前端·javascript·vue.js
张元清11 小时前
React useEventSource Hook:自带断线重连的 Server-Sent Events (2026)
javascript·react.js
学习星球11 小时前
Vue 3 实战:拆解 RealWorld 项目
前端·vue.js
铁皮饭盒11 小时前
网页端, 6.5MB人脸识别模型, 谷歌框架, 又快又准
前端·javascript·后端
自进化Agent智能体12 小时前
Hermes 工具与工具集——Hermes 的内置能力
javascript