el-table表格每一列前的多选框如何勾选和取消(易错点-两个坑)
el-table表格每一列前的多选框如何勾选和取消(易错点-两个坑)
·
比如我有一个表格如图:
场景一:如果我想回显选中的两条数据到表格中:
// 回显数据时
selectCarouselData() {
this.tempImgData.forEach(item => { // tempIngData是存着两条选中数据的数组
let imgUrl = item.imgUrl; // 每条数据的URL,这里是举个例子,找个唯一的id也可
this.carouselList.forEach(imgItem => { // 选中数据所组成的数组
if (imgItem.imgUrl === imgUrl) {
this.carouselList.toggleRowSelection(imgItem, true) // 将状态改为选中
}
})
})
}
场景二:将选中的数据取消勾选
这里有一个易错点,你可能会这样写:
1. 拿到表格本行数据row
2. this.carouselList.toggleRowSelection(row, false)
(以为将本行设置为false就行了)
错误,大错特错!!!
因为你此时的row
跟carouseList
中的键值对名称可能都对不上,所以这样写根本不生效,根本无法取消选中!!
正确示范:
this.carouselList.forEach(imgItem => {
if (imgItem.id == row.id) {
// 对比成功之后,取消选中
this.carouselList.toggleRowSelection(imgItem, false)
// 取消选中后还要把数据删除,否则url还是传成功了
this.tempImgData.splice(this.tempImgData.findIndex((item) => item.id === row.id), 1)
// 这里记得先findIndex拿到index,否则直接否则直接splice(imgItem,1)是会删除失败的!
}
})
易错点:
这里记得先findIndex
拿到index
,否则直接splice(imgItem,1)
是会删除失败的!因为splice
的参数传的不是删除的数据,而是要删除数据的index
。
场景三、清空所有选择:
this.$refs.list.clearSelection(); // el-table上绑定ref="list"
OK,这样就能实现,选中和取消选中了,记得避免这俩坑哦,共勉!
更多推荐
已为社区贡献2条内容
所有评论(0)