如果不需要回显
直接设置reserve-selection 为true
如果需要回显
1.reserve-selection 设置为false
2.需要设置row-key
3.定义2个变量selectList,selectAllIds
selectAllIds 保存唯一的id
selectList 保存勾选的值
4.el-table里增加事件
@select=“handleSelectionChange”
@select-all=“handleAllChange”
5.注意不要使用select-change
利用@select的第二个参数来增减selectAllIds, selectList里的值,确保都是勾选上的
注意
6.selectList,selectAllIds初始化的时候要塞入回显的值
7.利用toggleRowSelection勾选数据(需要放入翻页的事件里)
注意下面的例子显示的是已经封装过的el-table
<sys-table
:loading="loading"
:data="tableData"
:columns="tableColumns"
:num="params.currPage"
:pageSize="params.pageSize"
:pageTotal="pageTotal"
:height="tableHeight"
@onChange="handleChange"
row-key="id"
@select="handleSelectionChange"
@select-all="handleAllChange"
:pageSizes="[2, 10, 15]"
ref="table"
>
<template #projectName="{ scope }">
<el-link type="primary" @click="handleView(scope.row.id)">
{{ scope.row.projectName }}
</el-link>
</template>
</sys-table>
getBillList(this.params).then(res => {
if (res && res.status === '0') {
this.tableData = res.data.records
this.pageTotal = Number(res.data.total)
this.toggleData()
} else {
this.tableData = []
this.pageTotal = 0
}
this.loading = false
})
// 勾选或不勾选
handleSelectionChange(selection, row) {
// 每次勾选都需要判断是否勾选了已经选中的数据
if (!this.selectAllIds.includes(row.id)) {
this.selectList.push(row)
this.selectAllIds.push(row.id)
} else {
const index = this.selectAllIds.findIndex(item => {
return item === row.id
})
const indexList = this.selectList.findIndex(item => {
return item.id === row.id
})
this.selectAllIds.splice(index, 1)
this.selectList.splice(indexList, 1)
}
},
handleAllChange(selecteds) {
if (selecteds.length > 0) {
const tempList = []
selecteds.forEach(item => {
if (!this.selectAllIds.includes(item.id)) {
tempList.push(item.id)
this.selectList.push(item)
}
})
this.selectAllIds = [...this.selectAllIds, ...tempList]
} else {
this.tableData.forEach(item => {
this.selectAllIds.forEach((id, index) => {
if (id === item.id) {
this.selectList.splice(index, 1)
}
})
})
this.selectAllIds = this.selectAllIds.filter(item => {
const obj = this.tableData.find(itemData => {
return itemData.id === item
})
return !obj
})
}
},
toggleData() {
this.$refs.table.toggleSelection(this.selectAllIds, 'id')
},
private toggleSelection(rows: any, id: string = 'id') {
this.$nextTick(() => {
if (rows) {
rows.forEach((row: any) => {
const data: any[] = Array.from(this.$attrs.data)
const obj = data.find((item: any) => {
return item[id] === row
})
if (obj) {
;(this.$refs.table as any).toggleRowSelection(obj, true)
}
})
} else {
;(this.$refs.table as any).clearSelection()
}
})
}