使用element 中Tree 树形控件时,有时候后端接口没有返回嵌套好的树形结构,而是返回一级的数据源,那我们前端该如何处理呢?
重点是调用filters递归函数,代码如下所示:
<!DOCTYPE html>
<html>
<head>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<meta charset="UTF-8">
<!-- import CSS -->
<style>
</style>
</head>
<body>
<div id="app">
<el-tree :data="data"></el-tree>
</div>
</body>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
new Vue({
el: '#app',
data: function () {
return {
data: [],
newArr: [],
oldArr: [ //原始数据,pid是父级id
{
id: "1",
pid: "0",
label: "一级A"
},
{
id: "1-1",
pid: "1",
label: "一级A-A"
},
{
id: "1-1-1",
pid: "1-1",
label: "一级A-A-A"
},
{
id: "1-1-1-1",
pid: "1-1-1",
label: "一级A-A-A-A"
},
{
id: "1-2",
pid: "1",
label: "一级A-B"
},
{
id: "1-2-1",
pid: "1-2",
label: "一级A-B-A"
},
{
id: "2",
pid: "0",
label: "一级B"
},
{
id: "2-1",
pid: "2",
label: "一级B-A"
}
]
}
},
mounted() {
this.fun()
},
methods: {
filters(arr) {
this.newArr = arr.filter((item, itemIndex) => {
this.oldArr.forEach((oldItem, oldIndex) => {
if (oldItem.pid == item.id) { //有子节点,oldItem是item的子项
item.children.push(oldItem)
}
if (oldIndex == this.oldArr.length - 1) { //内层循环最后一项处理完毕
if (item.children && item.children.length) {//当前层级有子项,子项不为空
this.filters(item.children); //调用递归过滤函数
}
}
});
return true //返回过滤后的新数组赋值给this.newArr
})
return this.newArr
},
fun() {
let arr = []
this.oldArr.forEach((item1) => {
item1.children = []
if (item1.pid == 0) {
arr.push(item1)
}
});
this.data = this.filters(arr); //调用递归过滤函数
console.log(this.data, "组装后数据");
}
},
})
</script>
</html>