Recursion can hurt our heads. It’s especially tough when we have to use recursion to display tree structures the way we want.
In this article, we’ll look at how to build a very simple tree view with Vue.js
To get started, we have to create a component to display the tree nodes.
We can do that by create a Tree component in components/Tree.vue
:
<template>
<div>
<ul>
<li v-for="i of items" :key="i.name">
{{i.name}}
<Tree :items="i.children" v-if="i.children"/>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "Tree",
props: {
items: Array
}
};
</script>
We have a ul element, which renders the name
property of some object in a li.
Then it renders the children
property, which is an array with objects with the name
and children
properties like the current node.
As indicated by the props
property, our component takes an items
prop, which is an array.
In the li, we pass in the i.chilren
into the items
prop to render the items one level down.
We check if i.children
is defined so that Tree
will only render recursively if it’s defined.
Also, we display the i.name
value in the current component instance.
The name
property is required for recursive components.
Therefore, we should have that.
Then we can create our App.vue
component, which renders the root node.
To implement it, we write:
<template>
<div id="app">
<Tree :items="items"/>
</div>
</template>
<script>
import Tree from "./components/Tree";
export default {
name: "App",
components: {
Tree
},
data() {
return {
items: [
{
name: "foo",
children: [
{ name: "bar", children: [{ name: "baz" }, { name: "qux" }] }
]
},
{
name: "lorem",
children: [{ name: "ipsum" }]
},
{
name: "dolor"
}
]
};
}
};
</script>
We have an items
array, which is a nested array with objects that have the name
and children
properties.
The children
property has arrays with objects that have the same properties.
This is why we wrote out Tree
component the way we have before.
children
are rendered recursively, and name
is rendered in the current node.
We just pass items
straight into the items
prop of Tree
without changes.
Now we should see a nested list of words displayed on the page in the same order and levels that they’re defined in items
.