<template>
<div>
<el-button @click="handleOpen">open</el-button>
<el-table :data="outerList" style="width: 400px">
<el-table-column prop="id" label="id" />
<el-table-column prop="name" label="name" />
</el-table>
<el-dialog v-model="dialogVisible" title="Tips" width="500">
<el-table
ref="multipleTableRef"
v-loading="loading"
:data="tableData"
style="width: 100%"
@select="handleSingleSelect"
@select-all="handleAllSelect"
>
<el-table-column type="selection" width="55" />
<el-table-column prop="id" label="id" />
<el-table-column prop="name" label="name" />
</el-table>
<el-button @click="getList(1)">1</el-button>
<el-button @click="getList(2)">2</el-button>
<template #footer>
<div class="dialog-footer">
<el-button type="primary" @click="handleConfirm">
Confirm
</el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup>
import { nextTick, ref } from "vue";
const loading = ref(false);
const multipleTableRef = ref();
const dialogVisible = ref(false);
// 外层表哥数据
const outerList = ref([
{ id: 1, name: "1" },
{ id: 2, name: "2" },
]);
// checkbox已选数据
const chosenList = ref([]);
// 里层表哥数据
const tableData = ref([]);
const handleOpen = () => {
dialogVisible.value = true;
chosenList.value = JSON.parse(JSON.stringify(outerList.value));
getList(1);
};
// 获取列表数据
const getList = (page) => {
loading.value = true;
setTimeout(() => {
if (page === 1) {
tableData.value = [
{ id: 1, name: "1" },
{ id: 2, name: "2" },
];
} else {
tableData.value = [
{ id: 3, name: "3" },
{ id: 4, name: "4" },
];
}
loading.value = false;
// 等待tableData.value被赋值,DOM更新后再设置默认勾选
nextTick(() => {
toggleSelection(tableData.value);
});
}, 500);
};
const toggleSelection = (rows) => {
if (!rows) return multipleTableRef.value.clearSelection();
rows.forEach((row) => {
let has = chosenList.value.some((it) => it.id === row.id);
if (has) {
multipleTableRef.value.toggleRowSelection(row, true);
} else {
multipleTableRef.value.toggleRowSelection(row, false);
}
});
};
const handleSingleSelect = (selection, row) => {
// 是否选中/取消选中
let isAddRow = selection.some((it) => it.id === row.id);
// 取消选中
if (!isAddRow) {
// 移除之前选中的当前页的所有数据
let index = chosenList.value.findIndex((it) => it.id === row.id);
if (index > -1) chosenList.value.splice(index, 1);
return;
}
// 有值就是选中 且 没添加过则添加
for (let i of selection) {
let has = chosenList.value.some((it) => it.id === i.id);
if (!has) chosenList.value.push(i);
}
};
const handleAllSelect = (selection) => {
// 有值就是全选
if (selection.length) {
// 没添加过此条数据则添加
for (let i of selection) {
let has = chosenList.value.some((it) => it.id === i.id);
if (!has) chosenList.value.push(i);
}
}
// 清空
else {
// 循环当前列表数据,删除之前添加过的每一项
for (let i of tableData.value) {
let index = chosenList.value.findIndex((it) => it.id === i.id);
if (index > -1) chosenList.value.splice(index, 1);
}
}
};
// 确认
const handleConfirm = () => {
outerList.value = chosenList.value;
dialogVisible.value = false;
};
</script>
网友评论