Reputation: 11
I'm trying to create a vue js application where a treeview is displayed to the user. The elements inside the treeview can contain other elements, that can contain other elements etc ... With no limit, which means that the depth of the treeview is not known. If I'm right, it means I can't simply use the v-for directive (because it implies to know the depth right ?)
So i'm basically looping going through a json array and creating <ul>
and <li>
tags to append them to some other tag in the DOM, but if I do this, they don't get the styles of their class applied to them.
I suppose it's because Vue doesn't like the fact that we modify the DOM without having vue doing it for us.
Also, We don't want to use components libraries like vuetify, we want to do it with vue only and simple javascript.
Thank you !
Upvotes: 1
Views: 1569
Reputation: 4406
This is actually pretty straight forward in Vue.js.
What you have to do is simply create a component that invokes itself but changing the v-for to use the current tree branch's children.
An important step for making this work in Vue is to apply the name key to the component. Otherwise, the component can not invoke itself.
I have provided a simple example below using HTML's neat details
element.
// Your recursive branch component "branch.vue"
const branch = {
name: 'branch',
props: {
branch: {
type: Object,
default: () => ({}),
},
},
template: `
<details>
<summary>{{ branch.title }}</summary>
<branch
v-for="branch in branch.children"
:key="branch.title"
:branch="branch"
/>
</details>
`,
}
// Your page view(component) where you want to display the tree
new Vue({
el: '#app',
name: 'tree',
components: {
branch,
},
data() {
return {
tree: [
{
title: 'parent 1',
children: [
{
title: 'child 1',
children: [
{
title: 'child 1-1',
children: [],
},
{
title: 'child 1-2',
children: [],
},
],
},
],
},
],
};
},
})
#app > details {
margin-left: 0;
}
details {
margin-left: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<branch v-for="branch in tree" :key="branch.title" :branch="branch" />
</div>
Upvotes: 1
Reputation: 46
The solution is to create a recursive component, for example see here and here
Upvotes: 0