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>
相关推荐
瘦的可以下饭了26 分钟前
Day01-API
javascript
Nan_Shu_6141 小时前
学习:Vue (2)
javascript·vue.js·学习
北辰alk1 小时前
Vue项目Axios封装全攻略:从零到一打造优雅的HTTP请求层
vue.js
老华带你飞2 小时前
出行旅游安排|基于springboot出行旅游安排系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring·旅游
一水鉴天3 小时前
整体设计 定稿 之24+ dashboard.html 增加三层次动态记录体系仪表盘 之2 程序 (Q208 之2)
开发语言·前端·javascript
JIngJaneIL3 小时前
基于Java饮食营养管理信息平台系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
老华带你飞3 小时前
垃圾分类|基于springboot 垃圾分类系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring
二狗哈3 小时前
Cesium快速入门17:与entity和primitive交互
开发语言·前端·javascript·3d·webgl·cesium·地图可视化
GISer_Jing4 小时前
AI驱动营销增长:7大核心场景与前端实现
前端·javascript·人工智能
星光不问赶路人4 小时前
new Array() 与 Array.from() 的差异与陷阱
javascript·面试