在使用element做表格开发使用复选框和树形结构时发现点击父元素复选框时,子元素无法选中,于是在table上监听点击和全选,根据数据有子节点来手动切换选中与否。
HTML
<el-table
ref="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: 'childList'}">
<el-table-column
type="selection"
width="55">
</el-table-column>
<el-table-column
prop="date"
label="日期"
sortable
width="180">
</el-table-column>
<el-table-column
prop="name"
label="姓名"
sortable
width="180">
</el-table-column>
<el-table-column
prop="address"
label="地址">
</el-table-column>
</el-table>
{{ selectArr.map(el => el.id) }}
<div style="margin-top: 20px">
<el-button @click="cancelAll()">取消选择</el-button>
</div>
JS
export default {
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 弄',
childList: [{
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 弄'
}],
selectArr: []
},
methods: {
select (selection, row) {
if (selection.some(el => { return row.id === el.id })) {
if (row.childList) {
row.childList.map(j => {
this.toggleSelection(j, true)
})
}
} else {
if (row.childList) {
row.childList.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.childList) {
el.childList.map(j => {
this.toggleSelection(j, true)
})
}
})
}
if (isCancel) {
this.tableData.map(el => {
if (el.childList) {
el.childList.map(j => {
this.toggleSelection(j, false)
})
}
})
}
},
selectionChange (selection) {
this.selectArr = selection
},
toggleSelection (row, select) {
if (row) {
this.$nextTick(() => {
this.$refs.table && this.$refs.table.toggleRowSelection(row, select)
})
}
},
cancelAll () {
this.$refs.table.clearSelection()
}
}
}
- row-key: 渲染树形数据时,必须要指定 row-key, row-key的值必须是唯一的,可以是String类型,也可以是function(row)
- indent: 展示树形数据时,树节点的缩进, Number类型
- tree-props: 渲染嵌套数据的配置选项。:tree-props="{children: 'children'}"定义子项的List名字,在data内写入,即可将子项写入在表格中
- select-on-indeterminate:在多选表格中,当仅有部分行被选中时,点击表头的多选框时的行为。若为 true,则选中所有行;若为 false,则取消选择所有行
- toggleRowSelection:用于多选表格,切换某一行的选中状态,如果使用了第二个参数,则是设置这一行选中与否(selected 为 true 则选中)
- clearSelection:用于多选表格,清空用户的选择