el-table 表格
为 select 和 select-all 设置回调函数
<el-table :data="tableData" id="yc_load" ref="yc_load" height="500px" border default-expand-allrow-key="showId" :tree-props="{children: 'children'}"@select="select"@select-all="selectAll"><el-table-column type="selection" width="50"></el-table-column><el-table-column label="姓名" :fixed="true" prop="showName" align="left" header-align="left" width="230"></el-table-column>
</el-table>
简要数据格式
tableData: [{showId: xxx,showName: xxx,children: [{showId:xxx,showName:xxx,parentId:xxx},{showId:xxx,showName:xxx,parentId:xxx}]},{showId: xxx,showName: xxx}
],
ids: []
单选
select(selection,row){let vm = this// 操作行 row 在 已选范围 selection 内,认为是选中,否则是取消选中 if(selection.some((el)=>row.showId===el.showId)){// 设置当前行选中状态row.isChecked = true// 记录选中id this.addId(row)// 若存在子级,自己全选if(row.children) {row.children.map(c => {this.$refs.yc_load.toggleRowSelection(c,true)c.isChecked = truethis.addId(c)})}// 若存在父级,设置父级选中if(row.parentId){let pNode = vm.tableData.find(x => x.showId === row.parentId)this.$refs.yc_load.toggleRowSelection(pNode,true)pNode.isChecked = truethis.addId(pNode)}} else {row.isChecked = falsethis.deleteId(row)// 若存在子级,子级全部取消选中if(row.children){row.children.map((i)=>{this.$refs.yc_load.toggleRowSelection(i,false)i.isChecked = falsethis.deleteId(i)})}// 若存在父级,判断父级的子级(当前行的兄弟) ,若全部未选中,取消父级选中if(row.parentId) {let pNode = vm.tableData.find(x => x.showId === row.parentId)if(!pNode.children.some(el => el.isChecked == true)) {this.$refs.yc_load.toggleRowSelection(pNode,false)pNode.isChecked = falsethis.deleteId(pNode)}}}console.log(this.ids)
}
全选
selectAll(selection) {// 判断当前是否有已选中的let rA = this.tableData.some(el => {let r = falseif(el.children) {r = el.children.some(e => e.isChecked)}if(r) return rreturn el.isChecked})// 若有选中则全部取消,否则全部选中if(rA) {this.tableData.forEach(el => {el.isChecked = falsethis.$refs.yc_load.toggleRowSelection(el, false)this.deleteId(el)if(el.children) {el.children.forEach(e => {e.isChecked = falsethis.$refs.yc_load.toggleRowSelection(e, false)this.deleteId(e)})}})} else {this.tableData.forEach(el => {el.isChecked = truethis.$refs.yc_load.toggleRowSelection(el, true)this.addId(el)if(el.children) {el.children.forEach(e => {e.isChecked = truethis.$refs.yc_load.toggleRowSelection(e, true)this.addId(e)})}})}console.log(this.ids)
}
操作 ids
// 增加选中addId(o) {let id = o.showIdif(this.ids.indexOf(id) < 0) {this.ids.push(id)}},// 删除选中deleteId(o) {let id = o.showIdthis.ids = this.ids.filter(item => item !== id);},
不再设置 selection-change 回调函数,直接监听ids
// 监听idswatch: {ids: function (newVal, oldVal) {this.handleChange(newVal)}},
感谢 element-ui el-table 实现全选且父级子级联动 提供的思路
另附 el-table 文档