效果展示
代码
<el-table
ref="multipleTable"
v-loading="dataListParams.loading"
:data="dataList"
:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
border
default-expand-all
row-key="pk_id"
@select="rowSelect"
@select-all="selectAll"
>
data() {
return {
originalData: [],
dataList: [],
}
},
export function translateDataToTree(list, pKey = 'parent_id') {
let data = JSON.parse(JSON.stringify(list))
const parent = data.filter(
(value) =>
value[pKey] === 'undefined' || value[pKey] == null || value[pKey] == 0
)
const children = data.filter(
(value) =>
value[pKey] !== 'undefined' && value[pKey] != null && value[pKey] > 0
)
const translator = (parent, children) => {
parent.forEach((parent) => {
children.forEach((current, index) => {
if (current[pKey] === parent.pk_id) {
const temp = JSON.parse(JSON.stringify(children))
temp.splice(index, 1)
translator([current], temp)
typeof parent.children !== 'undefined'
? parent.children.push(current)
: (parent.children = [current])
}
})
})
}
translator(parent, children)
return parent
}
export function translateTreeToData(list) {
let data = JSON.parse(JSON.stringify(list))
const result = []
data.forEach((item) => {
const loop = (data) => {
const child = data.children
if (child) {
for (let i = 0; i < child.length; i++) {
loop(child[i])
}
delete data.children
}
result.push(data)
}
loop(item)
})
return result
}
rowSelect(selection, row) {
this.selectByRecursion(row, !row.isChecked)
this.isCheckParent(selection, row)
},
selectAll(selection) {
let firstMenu = selection.filter((item) => item.parent_id === 0)
this.$refs.multipleTable.data.map((items) => {
this.selectByRecursion(
items,
firstMenu.length === this.dataList.length
)
})
},
selectByRecursion(startItem, status) {
this.$refs.multipleTable.toggleRowSelection(startItem, status)
startItem.isChecked = status
if (startItem.children) {
startItem.children.forEach((item) =>
this.selectByRecursion(item, status)
)
}
},
isCheckParent(selection, row) {
if (row.parent_id === 0) return
let allChild = this.originalData.filter(
(item) => item.parent_id === row.parent_id
)
let selectChild = selection.filter(
(item) => item.parent_id === row.parent_id
)
let parentItem = this.getParentItem(
this.$refs.multipleTable.data,
row.parent_id
)
if (row.isChecked) {
if (selectChild.length === allChild.length) {
this.$refs.multipleTable.toggleRowSelection(parentItem, true)
parentItem.isChecked = true
}
} else {
if (selectChild.length !== allChild.length) {
this.$refs.multipleTable.toggleRowSelection(parentItem, false)
parentItem.isChecked = false
}
}
},
getParentItem(list, pId, pItem = null) {
list.some((item) => {
if (item.pk_id === pId) {
pItem = item
return true
} else if (item.children && item.children.length > 0) {
pItem = this.getParentItem(item.children, pId, pItem)
return !!pItem
} else {
return false
}
})
return pItem
},