准备数据_我们需要创建一个表示父子关系的数据列表_这个函数会遍历列表找到每个节点的子节点并正确地组织它们
一、准备数据
我们需要创建一个表示父子关系的数据列表。这里我们假设有一个如下所示的数据结构: ```json [ { id: 1, pid: null, name: "Root" }, { id: 2, pid: 1, name: "Child 1" }, { id: 3, pid: 1, name: "Child 2" }, { id: 4, pid: 2, name: "Grandchild 1" }, { id: 5, pid: 3, name: "Grandchild 2" } ] ``` 在这个例子中,每个对象都有一个`id`和一个`pid`,其中`pid`指向其父节点的`id`。二、编写递归函数
我们需要一个递归函数来将这个列表转换成树形结构。这个函数会遍历列表,找到每个节点的子节点,并正确地组织它们。 ```javascript function listToTree(list, pid) { let tree = []; let map = {}; list.forEach(item => { map[item.id] = {...item, children: []}; }); for (let i = 0; i < list.length; i++) { let { id, pid } = list[i]; if (pid === null) { tree.push(map[id]); } else { if (map[pid].children) { map[pid].children.push(map[id]); } } } return tree; } ```三、在组件中使用递归函数
接下来,我们可以在Vue组件中使用这个递归函数来生成树形结构,并在页面上展示它。 ```javascript export default { data() { return { list: [ { id: 1, pid: null, name: "Root" }, { id: 2, pid: 1, name: "Child 1" }, { id: 3, pid: 1, name: "Child 2" }, { id: 4, pid: 2, name: "Grandchild 1" }, { id: 5, pid: 3, name: "Grandchild 2" } ], tree: [] }; }, created() { this.tree = listToTree(this.list, null); } } ```四、TreeNode 组件
然后,我们可以创建一个`TreeNode`组件来递归渲染树形结构。 ```html
{{ node.name }}
```