在element-ui 2.13中,樹形表格加複選框後,子結構沒法選中的問題。因而在table上監聽點擊和全選,根據數據有子節點來手動切換選中與否。
template以下:element-ui
<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>
data以下ui
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: []
script代碼以下this
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() }
有個問題手動切換選中會屢次切換表格的selection-change,
知足了基本效果,但願有其餘方法的留言
spa