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>
相关推荐
Warren986 分钟前
软件测试-Selenium学习笔记
java·javascript·笔记·学习·selenium·测试工具·安全
萌萌哒草头将军21 分钟前
有了它 ,我彻底告别了 try-finally 🔥🔥🔥
前端·javascript·vue.js
老虎062736 分钟前
JavaWeb前端02(JavaScript)
开发语言·前端·javascript
anyup1 小时前
🔥🔥 10 天 Star 破百!uView Pro 文档也开源啦:完全免费、无广告、高效上手
前端·vue.js·uni-app
Python私教1 小时前
YggJS RLogin暗黑霓虹主题登录注册页面 版本:v0.1.1
开发语言·javascript·ecmascript
南半球与北海道#1 小时前
el-table合并单元格
javascript·vue.js·elementui·表格合并
Jimmy2 小时前
客户端存储 - IndexedDB
前端·javascript·indexeddb
成小白2 小时前
前端实现两个页面之间的通讯
前端·javascript
啷咯哩咯啷2 小时前
element-plus el-tree-v2大数据量勾选节点卡顿问题
前端·javascript·vue.js
EndingCoder3 小时前
测试 Next.js 应用:工具与策略
开发语言·前端·javascript·log4j·测试·全栈·next.js