-
-
Save uno-de-piera/2d5c7bfe3ee21b7555586f4a1a0d7e28 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div> | |
<ul v-if="treeData.length"> | |
<tree-node v-for="node in treeData" :node="node"></tree-node> | |
</ul> | |
</div> | |
</template> | |
<script> | |
import TreeNode from "./TreeNode"; | |
export default { | |
name: "TreeView", | |
components: {TreeNode}, | |
mounted() { | |
const data = [ | |
{ id: 1, name: "Elemento 1", parentId: null }, | |
{ id: 2, name: "Elemento 2", parentId: null }, | |
{ id: 3, name: "Elemento 3", parentId: null }, | |
{ id: 4, name: "Elemento 4", parentId: 1 }, | |
{ id: 5, name: "Elemento 5", parentId: 1 }, | |
{ id: 6, name: "Elemento 6", parentId: 2 }, | |
{ id: 7, name: "Elemento 7", parentId: 3 }, | |
{ id: 8, name: "Elemento 8", parentId: 3 }, | |
{ id: 9, name: "Elemento 9", parentId: 3 }, | |
{ id: 10, name: "Elemento 10", parentId: 4 }, | |
{ id: 11, name: "Elemento 11", parentId: 5 }, | |
{ id: 12, name: "Elemento 12", parentId: 5 }, | |
{ id: 13, name: "Elemento 13", parentId: null }, | |
{ id: 14, name: "Elemento 14", parentId: 13 }, | |
{ id: 15, name: "Elemento 15", parentId: 14 }, | |
{ id: 16, name: "Elemento 16", parentId: 15 }, | |
{ id: 17, name: "Elemento 17", parentId: 16 }, | |
]; | |
this.treeData = this.generateTree(data); | |
}, | |
data() { | |
return { | |
treeData: [] | |
}; | |
}, | |
methods: { | |
generateTree(data) { | |
let map = {}, | |
node, | |
roots = [], | |
i; | |
for (i = 0; i < data.length; i++) { | |
map[data[i].id] = i; | |
data[i].children = []; | |
} | |
for (i = 0; i < data.length; i++) { | |
node = data[i]; | |
if (node.parentId) { | |
if (node.parentId) { | |
data[map[node.parentId]].children.push(node); | |
} | |
} else { | |
roots.push(node); | |
} | |
} | |
return roots; | |
} | |
} | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment