注:
"vue": "^2.6.10",
"element-ui": "^2.11.0"
一、从后端拿到的数据结构
要求:
根据id和parentId的关系确定树形结构,id为ws-root的是顶层节点。`
const arrs = [
{ id: "ws-root", name: "我是根节点", icon: "" },
{
id: "1",
name: "1====第一层的子节点",
parentId: "ws-root",
icon: "el-icon-date"
},
{ id: "2", name: "2====第一层的子节点", parentId: "ws-root" },
{ id: "3", name: "3====第二层的子节点", parentId: "1" },
{ id: "4", name: "4====第三层的子节点", parentId: "3" }
];
二、实现的树形结构如下:
二、代码实现如下:
test.vue
如下:
<template>
<div>
<el-tree
class="_tree"
:data="treeList"
:props="defaultProps"
node-key="id"
:highlight-current="true"
ref="category"
>
<span slot-scope="{ node, data }">
<!--el-icon-fa-folder是默认的图标名,当数据的icon为空不存在的时候,默认显示它-->
<i :class="data.icon ? data.icon : 'el-icon-fa-folder'"></i>
<span class="tree_label">{{ node.label }}</span>
</span>
</el-tree>
</div>
</template>
<script>
import { formTreeByParentId } from "@/utils/formTheTree.js";
export default {
data() {
return {
defaultProps: {
children: "children",
label: "name"
},
treeList: []
};
},
mounted() {
this.getComnTree(this.treeInfo);
},
methods: {
getComnTree() {
const arrs = [
{ id: "ws-root", name: "我是根节点", icon: "" },
{
id: "1",
name: "1====第一层的子节点",
parentId: "ws-root",
icon: "el-icon-date"
},
{ id: "2", name: "2====第一层的子节点", parentId: "ws-root" },
{ id: "3", name: "3====第二层的子节点", parentId: "1" },
{ id: "4", name: "4====第三层的子节点", parentId: "3" }
];
this.treeList = formTreeByParentId(arrs);
}
}
};
</script>
<style lang="scss">
._tree {
color: #444;
padding-left: 15px;
span {
color: $icon_color;
}
i {
margin-right: 6px;
}
.tree_label {
font-size: 14px;
color: #333;
}
}
/* 重写Tree组件的icon样式*/
.el-icon-fa-folder:before {
content: "\F07B";
color: #008ecd;
}
</style>
formTheTree.js
文件内容如下:
/**
*
* @param {*} records - 数组数据
* @param {*} id - 上级id
* @returns - 返回树形菜单chidren
*/
function getChilds(records, id) {
let childs = [];
records.forEach((val) => {
id === val.parentId && childs.push({ ...val });
});
childs.forEach((childNode) => {
let currNode = getChilds(records, childNode.id);
currNode.length > 0 && (childNode.children = currNode);
});
return childs;
}
/**
*顶层节点依据: 传入的rootId为顶层节点,数据的parentId为rootId的时候,说明该条数据是顶层节点的下一层
* @param {Array} records - 数组数据
* @param {string} rootId - 根节点id
* @returns {Array} 返回结果数据
*/
export function formTreeByParentId(records, rootId) {
var result = [];
records.forEach((val) => {
if (val.parentId === rootId) {
let parent = { ...val };
parent.children = getChilds(records, val.id);
result.push(parent);
}
});
return result;
}
树形菜单效果如图:
参考了:博客