1. 使用 ref 来创建一个响应式的 ref 对象数组,用于存储每个 的 ref
2. 在 v-for 循环中,使用 ref 函数为每个表格创建一个唯一的 ref
3. 在点击按钮时,向数组中添加一个新的 ,并更新 ref 对象数组
<template>
<div>
<!-- 使用 v-for 循环渲染 el-table,并为每个表格分配一个动态的 ref -->
<el-table
v-for="(row, index) in tableData"
:key="index"
:data="row"
:ref="el => tableRefs[index] = el"
>
<!-- 表格列 -->
<template #default="{ row, $index }">
<el-button @clic="showTable($index)">查看当前ref</el-button>
</template>
</el-table>
<!-- 按钮用于添加新的表格 -->
<el-button @click="addTable">添加表格</el-button>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, Ref } from 'vue';
// 存储表格数据的响应式数组
const tableData = ref<Array<any[]>>([
// 初始表格的数据
[],
[],
[],
]);
// 存储表格 ref 的响应式对象数组
const tableRefs: Ref<InstanceType<any>> = ref([]);
// 如果有默认的表格 第一步先每个表格设置 ref
onMounted(() => {
tableData.value.forEach((_, index) => {
tableRefs.value[index] = ref<InstanceType<ElTable> | null>(null);
});
});
// 添加新的表格
const addTable = () => {
tableData.value.push([]);
tableRefs.value.push(ref<InstanceType<ElTable> | null>(null));
};
// 获取查看当前表格的 ref
const showTable= (index) => {
return tableRefs.value[index];
};
</script>