以id
作为唯一标识
模板
<el-table :data="data"
ref="table"
@select-all="selectAll"
@select="select"
style="width:100%">
<el-table-column type="selection"></el-table-column>
<el-table-column prop="id" label="id"></el-table-column>
</el-table>
变量
data: [],
selection: []
监听数据变动用于处理回显
watch: {
data(nv) {
//添加默认值
const vm = this
vm.$nextTick(d => {
vm.data.forEach(d => {
if (this.selection.includes(d.id)) {
vm.$refs['table'].toggleRowSelection(d, true)
}
})
})
}
}
处理复选逻辑
//length > 0 去重添加 length == 0 删除
selectAll(selection) {
const vm = this
if (selection.length) {
//去重添加
vm.selection = [...new Set([...vm.selection, ...selection.map(d => d.id)])]
} else {
//删除table中在selection 中缓存的内容
const delArr = this.data.map(d => d.id)
vm.selection = vm.selection.filter(d => !delArr.includes(d))
}
},
//有则删除,无则添加
select(selection, row) {
const vm = this
for (let i = 0; i < vm.selection.length; i++) {
if (vm.selection[i] == row.id) {
return vm.selection.splice(i, 1)
}
}
vm.selection.push(row.id)
}