给表格加事件
<el-table
ref="multipleTable"
:data="tableData"
tooltip-effect="dark"
style="width: 100%"
:default-sort="{ prop: 'date', order: 'descending' }"
:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
v-loading="loading"
:row-key="getRowKey"
@select="selectChange"
@select-all="selectAllChange"
@selection-change="handleSelectionChange"
>
<el-table-column type="selection" align="center" :reserve-selection="true" width="55"></el-table-column>
</el-table>
在mehods里给方法
// 手动勾选数据行
selectChange(selection, row) {
// 如果selection中存在row代表是选中,否则是取消选中
if (selection.find(val => { return this.getDataId(val) === this.getDataId(row) })) {
if (row.children) {//注意这里的children是后台返回数据的children字段
row.children.forEach(val => {
this.$refs.multipleTable.toggleRowSelection(val, true)
selection.push(val)
if (val.children) {
this.selectChange(selection, val)
}
})
}
} else {
this.toggleRowSelection(selection, row)
}
},
/**
* 用于树形表格多选, 选中所有
* @param selection
*/
selectAllChange(selection) {
// 如果选中的数目与请求到的数目相同就选中子节点,否则就清空选中
if (selection && selection.length === this.tableData.length) {
selection.forEach(val => {
this.selectChange(selection, val)
})
} else {
this.$refs.multipleTable.clearSelection()
}
},
/**
* 切换选中状态
* @param selection
* @param data
*/
toggleRowSelection(selection, data) {
if (data.children) {//注意这里的children也是后台返回数据的children字段
data.children.forEach(val => {
this.$refs.multipleTable.toggleRowSelection(val, false)
if (val.children) {
this.toggleRowSelection(selection, val)
}
})
}
},
// 表格id
getDataId(data) {
return data['id']
},
//数组去重
unique(arr,i){
for(let i=0;i<arr.length;i++){
for(let j=i+1;j<arr.length;j++){
if(arr[i].id == arr[j].id){
arr.splice(j,1)
j--
}
}
}
},
// 选择改变
handleSelectionChange(val) {
this.multipleSelection = val
this.unique(this.multipleSelection,'id')//这里有一个问题就是这样点选完之后,数据有重复,所以根据id手动去重
},
//选择分页
getRowKey(row) {
return row.id
},