// 獲取當前選中的所有父子節點(數組)
let sourceNodeList = this.$refs.tree.getCheckedAndIndeterminateNodes();
if (sourceNodeList.length > 0) {
let result = this.translateDataToTree(JSON.parse(JSON.stringify(sourceNodeList)));
} else {
this.$Message.warning({
content: '請先選擇要導出的資源'
});
}
// 根據父子id數組轉換成樹形結構
translateDataToTree(data) {
// 沒有父節點的數據
let parents = data.filter(value => value.parent == undefined || value.parent == null || value.parent == '#');
// 有父節點的數據
let childrens = data.filter(value => value.parent !== undefined && value.parent != null && value.parent != '#')
//定義轉換方法的具體實現
let translator = (parents, childrens) => {
// 遍歷父節點數據
parents.forEach((parent) => {
// 遍歷子節點數據
childrens.forEach((current, index) => {
// 此時找到父節點對應的一個子節點
if (current.parent === parent.id) {
// 對子節點數據進行深複製
let temp = JSON.parse(JSON.stringify(childrens))
// 讓當前子節點從temp中移除,temp作爲新的子節點數據,這裏是爲了讓遞歸時,子節點的遍歷次數更少,如果父子關係的層級越多,越有利
temp.splice(index, 1)
// 讓當前子節點作爲唯一的父節點,去遞歸查找其對應的子節點
translator([current], temp)
// 把找到子節點放入父節點的childResourceList屬性中
parent.childResourceList != null ? parent.childResourceList.push(current) : parent.childResourceList = [current]
}
})
}
)
}
translator(parents, childrens);
return parents;
}