直接上代码:
<template>
<div>
<ul>
<li v-for="list in datas(dataList)" :key="list.id">
<!-- {{list}} -->
<span>{{list.name}}</span>
<ul>
<li v-for="(item,index) in list.children" :key="index">
<span>{{item.name}}</span>
<ul>
<li v-for="(items,index) in item.children" :key="index">{{items.name}}</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
dataList: [
{ id: 1, parentId: null, name: "世界" },
{ id: 2, parentId: 1, name: "中国" },
{ id: 201, parentId: 2, name: "湖南" },
{ id: 202, parentId: 2, name: "广东" },
{ id: 3, parentId: 1, name: "US" },
{ id: 302, parentId: 3, name: "California" },
{ id: 308, parentId: 3, name: "Washington" }
]
};
},
computed: {
datas() {
return function translateDataToTree(data) {
let parents = data.filter(
value => value.parentId == "undefined" || value.parentId == null
);
let children = data.filter(
value => value.parentId !== "undefined" && value.parentId != null
);
let translator = (parents, children) => {
// 遍历父节点数据
parents.forEach(parent => {
// 遍历子节点数据
children.forEach((current, index) => {
// 当父节点对应的一个子节点相等时
if (current.parentId === parent.id) {
//对子节点数据进行深复制,防止当temp改变而改变子节点
let temp = JSON.parse(JSON.stringify(children));
// 让当前子节点从temp中移除,temp作为新的子节点数据
temp.splice(index, 1);
// 让当前子节点作为唯一的父节点,去递归查找其对应的子节点
translator([current], temp);
// 把找到子节点放入父节点的children属性中
typeof parent.children !== "undefined"
? parent.children.push(current)
: (parent.children = [current]);
}
});
});
};
// 调用转换方法
translator(parents, children);
//返回
return parents;
};
}
}
};
</script>
原文地址:https://www.cnblogs.com/drBlog/p/12568399.html