由于业务需求,elementUI提供的单页多选或单选,已经无法满足需求了,那就搬一下el-table这块砖啦
勾选效果的选择
可选项:checkbox、radio或者是表格行高亮
最终选择:checkbox
拍板原因:
radio ==》 重复点击没有交互效果,即选中了,无法取消选择;
表格行高亮 ==》 可以考虑在单选情况下使用,但是不能跟checkbox一起使用,交互效果会互斥。
代码拆解
data
pageIndex: 1,
pageTotal: 0,
selectId: '',
dataList: this.data,
backupList: [], // 已选中的全部obj
backupIds: [], // 已选中的全部ids
currentPage: [], // 当前页已选中的全部obj
otherPage: [] // 其他页已选中的全部obj
watch
this.dataList = val.map((i, k) => {
let obj = {
id: i.id
}
this.tableConfig.tableHead.forEach(key => {
obj[key.prop] = i[key.prop]
})
if (this.multiple) {
if (this.backupIds.indexOf(i.id) > -1) {
this.currentPage.push(i)
this.backupList.splice(this.backupIds.indexOf(i.id), 1)
this.backupIds.splice(this.backupIds.indexOf(i.id), 1)
this.$nextTick(function () {
this.$refs.checkboxTable.toggleRowSelection(this.dataList[k], true)
})
}
} else {
if (this.backupList.length > 0 && this.backupList[0].id === i.id) {
obj.chosed = true
} else {
obj.chosed = false
}
}
return obj
})
this.otherPage = this.backupList
method
handleSelectChange (selection, id) {
if (this.multiple) { // 多选
this.currentPage = selection
} else { // 单选
this.dataList = this.dataList.map(i => {
if (i.id === id) {
i.chosed = selection
if (selection) {
this.backupList = [i]
}
} else {
i.chosed = false
}
return i
})
}
},
handleCurrentPageChange (val) {
if (this.multiple) { // 多选
this.backupList = JSON.parse(JSON.stringify(this.currentPage.concat(this.otherPage)))
this.backupIds = this.backupList.map(i => i.id)
this.currentPage = [] // 当前页已选中的obj
this.otherPage = [] // 其他页已选中的obj
}
this.$emit('handleCurrentPageChange', val)
},
submitData () {
if (this.multiple) { // 多选
return JSON.parse(JSON.stringify(this.currentPage.concat(this.otherPage)))
} else {
return this.backupList
}
}
数据自动勾选的关键点
数据处理的时候,要自动选中已保存的数据,这个操作就需要用到 el-table 自带的方法 toggleRowSelection ,但这个方法需要在 $nextTick 中触发。由于用 toggleRowSelection 完成勾选或取消勾选的赋值操作时,其实只完成了数据模型的改变,并没有完成视图的更新,即 DOM 的更新循环还没有完成,来不及渲染新的 DOM ,从而导致视图无法同步新的数据,因此需要在 $nextTick 触发这个赋值操作,才能保证这个赋值操作是作用于新的 DOM 结构之上。