一个表格进行数据展示的时候(A表格),我们进行数据选择时,需要另个表格(B表格)保存所选的数据,那两个表格就需要进行联动。比如: A表格复选框选择,则B表格就新增一条,当A复选框失去选择,则B表格则删除对应的数据。但是当A表分页或者重新加载的时候,则B中的数据,需要在A的表格中进行选中。
代码:
A表格:
<el-table
v-loading="loading"
:data="targetTable"
style="width: 100%"
row-key="EXECUTION_STANDARD_ID"
border
stripe
ref="multipleTable"
height="100%"
:span-method="arraySpanMethod"
@select-all="selectALL"
@selection-change="handleSelectionChange">
</el-table>
当请求A表格的数据的时候,需要把B表中的数据进行选中操作
//注释:::::每次第一个表格的数据重新请求,则this.tableTemporaryList = [],一般写在请求第一个表格数据的位置。给第一个表格赋值时
getTemplateExecutionStandard() {
this.tableTemporaryList = []
if(this.activeTable.length >0) {
this.targetTable.forEach(item=>{
const index = this.activeTable.findIndex(x=>x.EXECUTION_STANDARD_ID == item.EXECUTION_STANDARD_ID)
if(index != -1) {
this.$nextTick(() => {
this.$refs.multipleTable.toggleRowSelection(item)
})
}
})
}
},
当A表格复选框全选的时候,需要进行一个判断
//复选框
selectALL(selection) {
if(selection.length > 0) {
selection.forEach(item=>{
const index = this.activeTable.findIndex(res=>res.EXECUTION_STANDARD_ID == item.EXECUTION_STANDARD_ID)
if(index == -1) {
this.activeTable.push(item)
}
})
}else {
this.targetTable.forEach(item=>{
if(item.NODE_ID) {
const index = this.activeTable.findIndex(res=>res.EXECUTION_STANDARD_ID == item.EXECUTION_STANDARD_ID)
if(index != -1) {
this.activeTable.splice(index, 1)
}
}
})
}
},
之后是复选框选择,因为selectChange方法每次给的都是选中的数据,当复选框删除某个数据的时候,我们则不知道了。这个时候就需要记录一下上次选中的数据,跟这次选择的数据,
//目标选择
handleSelectionChange(val) {
let maxLength = []
let minLength = []
let flag = ''
if(val.length > this.tableTemporaryList.length) {
maxLength = val;
minLength = this.tableTemporaryList
flag = 'add'
}else {
maxLength = this.tableTemporaryList
minLength = val
flag = 'delete'
}
const difference = this.getObjectArrayDifferenceById(maxLength, minLength)
if(difference.length == 1) {
const index = this.activeTable.findIndex(res=>res.EXECUTION_STANDARD_ID == difference[0].EXECUTION_STANDARD_ID)
if(flag == 'add') {
if(index == -1) {
this.activeTable.push(difference[0])
}
}else {
if(index != -1) {
this.activeTable.splice(index, 1)
}
}
}
this.tableTemporaryList = val
},
//对比两个数组
getObjectArrayDifferenceById(array1, array2) {
const ids2 = array2.map(obj => obj.EXECUTION_STANDARD_ID);
return array1.filter(obj => !ids2.includes(obj.EXECUTION_STANDARD_ID));
},
B表格: 这个表格就比较简单了。因为他只有删除操作。
<el-table
:data="activeTable"
style="width: 100%"
row-key="EXECUTION_STANDARD_ID"
border
stripe
height="100%">
<el-table-column
label="操作"
align="center"
width="50">
<template v-slot="scope">
<i class="el-icon-delete" @click="deleteTable(scope.row)"></i>
</template>
</el-table-column>
</el-table>
//删除检查项
deleteTable(row) {
for (let i=0; i<this.activeTable.length; i++) {
if(this.activeTable[i].EXECUTION_STANDARD_ID == row.EXECUTION_STANDARD_ID) {
this.activeTable.splice(i,1)
const item = this.targetTable.find(item=> item.EXECUTION_STANDARD_ID == row.EXECUTION_STANDARD_ID)
this.$refs.multipleTable.toggleRowSelection(item, false)
return
}
}
},