在一般的element ui 表格中数据选中后,翻译就没有了。今天来解决这个问题。
需求:左右都有一个表格。左边选中时,右边出现选中的的数据,翻页时,右边数据保留,再翻回来选中的数据勾起,删除右边表格的数据,左边相应数据取消勾选
大概效果:
左边表格代码
<el-table
:data="userTable"
ref="selectedUser"
:row-key="
(row) => {
return row.id;
}
"
@select="userSel"
@select-all="userAll"
style="width: 100%"
max-height="250"
>
<el-table-column type="selection" align="center"> </el-table-column>
<el-table-column prop="name" label="待选">
<template scope="scope">
{{ scope.row.name ? scope.row.name : scope.row.phone }}
</template>
</el-table-column>
</el-table>
<el-pagination
style="text-align: right; margin-top: 20px"
layout="prev, pager, next"
:total="usertotal"
@current-change="yema"
v-show="usertotal > 0"
:page-size="6"
>
</el-pagination>
row-key用不用好像都可以,不过多选框事件一定要@select和@select-all,select是单个复选框的事件,selectAll是全选框的事件。不能用@selection-change会重复保存。
select事件
// 左边用户多选改变事件
userSel(select, row) {
// console.log(select,row)
var selctIds = [];
if (select.length > 0) {
if (this.selected.length > 0) {
this.selected.forEach((item, index) => {
selctIds.push(item.id);
selctIds = [...new Set(selctIds)];
if (row.id == item.id) {
this.selected.splice(index, 1);
// console.log("删除");
}
});
if (selctIds.indexOf(row.id) == -1) {
this.selected.push(row);
// console.log("加入");
}
} else {
this.selected.push(row);
selctIds.push(row.id);
}
} else {
this.selected = [];
}
},
select-all事件
userAll(selection){
let selectAll=[]
if(selection.length==0){
selectAll=[]
// console.log(this.userTable)
// 取消全选时获取当前页的所有数据,在selected中删除
this.userTable.forEach((item,index)=>{
this.selected.forEach((ite,inde)=>{
if(item.id==ite.id){
this.selected.splice(inde,1)
}
})
})
}else{
selectAll=[...selection]
}
this.selected.forEach((item,index)=>{
selectAll.forEach((ite,inde)=>{
if(item.id==ite.id){
selectAll.splice(inde,1)
}
})
})
selectAll.forEach(item=>{
this.selected.push(item)
})
console.log(selectAll)
},
右边取消选中
// 右边取消选中
delUser(row) {
console.log(this.userTable);
this.userTable.forEach(item=>{
if(row.id==item.id){
this.$refs.selectedUser.toggleRowSelection(item, false);
}
})
this.selected.forEach((item,index)=>{
if(row.id==item.id){
this.selected.splice(index,1)
}
})
},
最后还有一个功能,翻页时已经选中的数据会勾选起,这个一定要在获取数据的地方判断,不能再翻页事件那边判断.
// 获取用户
getUser() {
selUser(this.userParmas).then((response) => {
this.userTable = response.rows;
this.usertotal = Number(response.total);
// console.log(this.userTable);
if (this.selected.length > 0) {
setTimeout(() => {
this.userTable.forEach((item) => {
this.selected.forEach((ite) => {
if (item.id == ite.id) {
this.$refs.selectedUser.toggleRowSelection(item, true);
}
});
});
}, 200);
// console.log(item)
}
});
},