<template>
<div>
<el-tree
ref="tree"
node-key="objectId"
:data="treeData"
:props="props"
:expand-on-click-node="false"
default-expand-all
highlight-current
></el-tree>
</div>
</template>
<script>
export default {
data(){
return{
data:[
{
createdAt: "2019-07-10T05:43:22.898Z",
name: "公安",
objectId: "rOYDUivsCb",
path: "",
updatedAt: "2019-07-10T05:43:22.898Z",
sort:0,
},
{
createdAt: "2019-07-15T06:58:30.615Z",
description: "",
name: "机构一",
objectId: "wuLLHGaVjs",
parent: "rOYDUivsCb",
permissions: [],
updatedAt: "2019-07-15T06:58:30.615Z",
sort:2
},
{
createdAt: "2019-07-15T06:58:40.671Z",
description: "",
name: "机构二",
objectId: "VvWhkeujpo",
parent: "wuLLHGaVjs",
permissions: [],
updatedAt: "2019-07-15T06:58:40.671Z",
sort:1
}
],
treeData:[],
props: {
label: "name"
}
}
},
async mounted(){
this.treeData = await this.toTree(this.data, "objectId", "parent","sort");
},
methods:{
//转换成树状结构所需要的data格式
toTree(objects, keyName, parentKeyName,sortKeyName) {
if (!keyName) {
throw "keyName argument is required";
}
if (!parentKeyName) {
throw "parentKeyName argument is required";
}
// 列表项字典 将数组变成以objectId分组的对象,类似于{Vvwkeujpo:{},Rohdsfdofj:{}}
var map = {};
var source = {};
objects.forEach(x => {
map[x[parentKeyName] + x[sortKeyName]] = Object.assign({}, x);
source[x[keyName]] = Object.assign({}, x);
});
// 已添加到父项的键
var pushed = {};
// 遍历列表项,将子项添加到父项的 children 数组
for (const key in map) {
if (map.hasOwnProperty(key)) {// 这样就可以过滤掉原型链上的可枚举属性了
const x = map[key];
if (x && x[keyName] && x[parentKeyName]>=0) {
var parent = source[x[parentKeyName]];
if (parent) {
if (!parent.children) {
parent.children = [];
}
parent.children.push(source[x[keyName]]);
pushed[x[keyName]] = true;
}
}
}
}
// 排除已添加到父项的项得到树
var tree = [];
for (const key in map) {
if (map.hasOwnProperty(key)) {
const x = map[key];
if (!pushed[x[keyName]]) {
tree.push(source[x[keyName]]);
}
}
}
return tree;
}
}
}
</script>
<style lang="scss" scoped>
.el-tree {
font-size: 13px;
background: #fafafa; // #eee;
padding: 5px;
// /deep/.tree_text {
// overflow: hidden;
// text-overflow: ellipsis;
// white-space: nowrap;
// display: inline-block;
// width: 80px;
// }
}
</style>
参照原博主的代码,做了下优化,能够保留后台数据的顺序,作为排序的字段是int类型