Tree components are very common and practical. Did you notice that not all tree components are nested?
Our goal is to visualize tree data structures in the browser.
<code class="language-javascript"> // 一个基本的树形数据结构 const treeData = { id: 0, name: "root", children: [ { id: 1, name: "node 1", children: [ { id: 3, name: "node 1.1" } ] }, { id: 2, name: "node 2", children: [ { id: 4, name: "node 2.1" } ] } ] };</code>
It has two child nodes, and each child node has a child node.
I initially assumed that the structure of the tree component was nested. This is the most intuitive way to generate a tree structure. Just iterate through the data structure and convert it into HTML elements.
<code class="language-javascript">function nestedTreeGenerator(treeData, depth) { const nodes = []; // ... (代码略,与原文相同) ... }</code>
It will generate the following HTML structure. This is a typical HTML structure and we can easily add collapse/expand functionality to the tree.
Flat tree is a list but looks like a tree.
<code class="language-javascript">function flatTreeGenerator(treeData, depth, parentId) { let nodes = []; // ... (代码略,与原文相同) ... }</code>
The end result will be the same as shown below. I saved the node ID and parent ID so we don't lose the hierarchy information. Indentation does not occur naturally, so you need to handle it yourself.
The two trees look identical. However, hover over a tree node and you'll notice a slightly different behavior. Nested trees always have a background color with indentation, flat trees don't.
After downloading VS Code, I learned about flat trees for the first time. I found that VS Code displayed my folder structure elegantly, it looked like a list but you could collapse/expand the folders. My favorite thing is that when you hover your cursor over a folder or file, the entire column is highlighted.
Using nested trees, you can easily implement tree-related functionality on it based on its hierarchical structure.
Flat trees look cleaner. Due to its simple structure, it is easy to apply CSS styles to it.
They each have advantages and disadvantages, please choose the appropriate type according to your needs.
The above is the detailed content of Nested Tree vs Flat Tree. For more information, please follow other related articles on the PHP Chinese website!