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>
相关推荐
平头哥技术团队7 小时前
Day 10 | 工欲善其事:VS Code 配置与项目归档
android·开发语言·前端·javascript·html·交互
yume_sibai7 小时前
Element Plus 数据展示组件完全指南(15个核心组件)
前端·javascript·vue.js
剑之所向10 小时前
.NET 官方`System.Threading.Channels`
前端·javascript·数据库
渡我白衣11 小时前
并查集:基础认识与模拟实现
android·java·javascript·数据结构·c++·算法·并查集
八角丶12 小时前
Node 网络编程 —— TLS 模块
javascript·后端·node.js
倔强的石头10612 小时前
【Linux指南】动静态库系列(七):符号表与重定位:链接器如何把函数调用接起来
linux·前端·javascript
图扑软件13 小时前
中篇・运笔|统一 DataModel 底座,HT UI 组件万物同源
javascript·低代码·ui·性能优化·数据可视化
小小尚@14 小时前
WebGIS/ECharts 地图开发|MapLand 在线行政区划边界一键下载 GeoJSON 工具
前端·javascript·echarts
葡萄城技术团队14 小时前
工业数据可视化:使用活字格 AIcoding + Three.js 构建轻量化三维设备监控大屏
开发语言·javascript·信息可视化
默_笙15 小时前
🚍 一条 Todo 的奇幻漂流:TypeScript 全栈类型安全的"护照检查"
前端·javascript