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>
相关推荐
2401_878454531 天前
浏览器工作原理
前端·javascript
by__csdn1 天前
Vue3 setup()函数终极攻略:从入门到精通
开发语言·前端·javascript·vue.js·性能优化·typescript·ecmascript
一条可有可无的咸鱼1 天前
企业招聘信息,企业资讯进行公示
java·vue.js·spring boot·uni-app
Luna-player1 天前
在前端中,<a> 标签的 href=“javascript:;“ 这个是什么意思
开发语言·前端·javascript
lionliu05191 天前
js的扩展运算符的理解
前端·javascript·vue.js
小草cys1 天前
项目7-七彩天气app任务7.4.2“关于”弹窗
开发语言·前端·javascript
前端一小卒1 天前
一个看似“送分”的需求为何翻车?——前端状态机实战指南
前端·javascript·面试
syt_10131 天前
Object.defineProperty和Proxy实现拦截的区别
开发语言·前端·javascript
长安牧笛1 天前
儿童屏幕时间管控学习引导系统,核心功能,绑定设备,设时长与时段,识别娱乐,APP超时锁屏,推荐益智内容,生成使用报告,学习达标解锁娱乐
javascript
老前端的功夫1 天前
Vue 3 vs Vue 2 深度解析:从架构革新到开发体验全面升级
前端·vue.js·架构