需要加以下三個(gè)方法
@select="selectChange"
@select-all="selectAllChange"
@selection-change="selectionChangeHandler"
<el-table
ref="multiTable"
v-loading="crud.loading"
lazy
:load="getMenus"
:data="list"
:tree-props="{children: 'children', hasChildren: 'hasChildren'}"
row-key="id"
@select="selectChange"
@select-all="selectAllChange"
@selection-change="selectionChangeHandler"
>
/**
* 用于樹形表格多選寓娩,單選的封裝
* @param selection
* @param row
*/
selectChange(selection, row) {
// 如果selection中存在row代表是選中,否則是取消選中
if (selection.find(val => { return this.getDataId(val) === this.getDataId(row) })) {
if (row.children) {//注意這里的children是后臺(tái)返回?cái)?shù)據(jù)的children字段
row.children.forEach(val => {
this.$refs.multiTable.toggleRowSelection(val, true)
selection.push(val)
if (val.children) {
this.selectChange(selection, val)
}
})
}
} else {
this.toggleRowSelection(selection, row)
}
},
/**
* 用于樹形表格多選, 選中所有
* @param selection
*/
selectAllChange(selection) {
// 如果選中的數(shù)目與請(qǐng)求到的數(shù)目相同就選中子節(jié)點(diǎn),否則就清空選中
if (selection && selection.length === this.list.length) {
selection.forEach(val => {
this.selectChange(selection, val)
})
} else {
this.$refs.multiTable.clearSelection()
}
},
// 選擇改變
selectionChangeHandler(val) {
this.selections = val
this.unique(this.selections,'id')//這里有一個(gè)問(wèn)題就是這樣點(diǎn)選完之后价涝,數(shù)據(jù)有重復(fù)恩沽,所以根據(jù)id手動(dòng)去重,期待優(yōu)化
},
/**
* 切換選中狀態(tài)
* @param selection
* @param data
*/
toggleRowSelection(selection, data) {
if (data.children) {//注意這里的children也是后臺(tái)返回?cái)?shù)據(jù)的children字段
data.children.forEach(val => {
this.$refs.multiTable.toggleRowSelection(val, false)
if (val.children) {
this.toggleRowSelection(selection, val)
}
})
}
},
getDataId(data) {
return data['id']
},
//數(shù)組去重
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--
}
}
}
}啸胧,
//列表樹懶加載
getMenus(tree, treeNode, resolve) {
const params = { pid: tree.id }
setTimeout(() => {
crudMenu.getMenus(params).then(res => {
resolve(res.content)
})
}, 100)
},