树形表格加复选框后,选中父节点后子节点不自动选中的问题。于是在table上监听点击和全选,根据数据有子节点来手动切换选中与否。
template如下
<template><divclass="divBox"><el-tableref="table":data="tableData"style="width: 100%;margin-bottom: 20px;"row-key="id"border:indent="50":select-on-indeterminate="false"@select="select"@select-all="selectAll"@selection-change="selectionChange"default-expand-all:tree-props="{children: 'children'}"><el-table-columntype="selection"width="55"></el-table-column><el-table-columnprop="date"label="日期"sortablewidth="180"></el-table-column><el-table-columnprop="name"label="姓名"sortablewidth="180"></el-table-column><el-table-columnprop="address"label="地址"></el-table-column></el-table>
{{ selectArr.map(el => el.id) }}
<divstyle="margin-top: 20px"><el-button@click="cancelAll()">取消选择</el-button></div></div></template>
data如下:
tableData: [{
id: 1,
date: '2016-05-01',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
}, {
id: 2,
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1517 弄'
}, {
id: 3,
date: '2016-05-03',
name: '王小虎',
address: '上海市普陀区金沙江路 1519 弄',
children: [{
id: 31,
date: '2016-05-31',
name: '王小虎',
address: '上海市普陀区金沙江路 1519 弄'
}, {
id: 32,
date: '2016-05-32',
name: '王小虎',
address: '上海市普陀区金沙江路 1519 弄'
}]
}, {
id: 4,
date: '2016-05-04',
name: '王小虎',
address: '上海市普陀区金沙江路 1516 弄',
children: [{
id: 41,
date: '2016-05-31',
name: '王小虎',
address: '上海市普陀区金沙江路 1519 弄'
}, {
id: 42,
date: '2016-05-32',
name: '王小虎',
address: '上海市普陀区金沙江路 1519 弄'
}]
}],
selectArr: []
}
methods方法如下:
select(selection, row){if(selection.some(el=>{return row.id === el.id })){if(row.children){
row.children.map(j=>{this.toggleSelection(j,true)})}}else{if(row.children){
row.children.map(j=>{this.toggleSelection(j,false)})}}},selectAll(selection){// tabledata第一层只要有在selection里面就是全选const isSelect = selection.some(el=>{const tableDataIds =this.tableData.map(j=> j.id)return tableDataIds.includes(el.id)})// tableDate第一层只要有不在selection里面就是全不选const isCancel =!this.tableData.every(el=>{const selectIds = selection.map(j=> j.id)return selectIds.includes(el.id)})if(isSelect){
selection.map(el=>{if(el.children){
el.children.map(j=>{this.toggleSelection(j,true)})}})}if(isCancel){this.tableData.map(el=>{if(el.children){
el.children.map(j=>{this.toggleSelection(j,false)})}})}},selectionChange(selection){this.selectArr = selection
console.log(this.selectArr,'selectArr')},toggleSelection(row, select){if(row){this.$nextTick(()=>{this.$refs.table &&this.$refs.table.toggleRowSelection(row, select)})}},cancelAll(){this.$refs.table.clearSelection()}}
文章描述了一个在Vue.js应用中处理树形表格的问题,当点击父节点时,子节点未自动选中。作者通过监听表格的点击和全选事件,结合数据判断来手动控制子节点的选中状态,实现了父子节点的联动。代码示例展示了如何使用`toggleSelection`方法来切换行的选中状态。
5996

被折叠的 条评论
为什么被折叠?



