this is what i have tried
Html
<ul >
<li>
<span>First Node</span>
<ul>
<li v-for="(tree, i) in trees" :key="i">
<span v-text="tree.name"></span>
<ul v-if="tree.childrens">
<li v-for="(child, j) in tree.childrens" :key="j">
<span v-text="child.name"></span>
</li>
</ul>
</li>
</ul>
</li>
</ul>
Javascript
I wanna loop every children without adding a new HTML element, but I have no idea how to do that.
export default {
data() {
return {
trees: [
{ name: 'Node A' },
{ name: 'Node B', childrens: [
{ name: 'Node B1' },
{ name: 'Node B2', childrens: [
{ name: 'Node B2.1' },
{ name: 'Node B2.2' },
] },
] },
],
};
},
};
Display
Anyone, thanks for your help
CodePudding user response:
You can achieve this requirement by using Circular References Between Components
concept of Vue. Where instead of creating a separate element for each children you can recursively call the child component.
Live Demo :
Vue.component('child', {
props: ['children'],
template: `<ul>
<li v-for="(child, index) in children" :key="index">
<parent v-if="child.childrens" :trees="[child]"></parent>
<span v-else>{{ child.name }}</span>
</li>
</ul>`
});
Vue.component('parent', {
props: ['trees'],
template: `<ul>
<li v-for="(tree, i) in trees" :key="i">
<span v-text="tree.name"></span>
<child v-if="tree.childrens" :children="tree.childrens"></child>
</li>
</ul>`
});
var app = new Vue({
el: '#app',
data: {
trees: [
{ name: 'Node A' },
{ name: 'Node B', childrens: [
{ name: 'Node B1' },
{ name: 'Node B2', childrens: [
{ name: 'Node B2.1' },
{ name: 'Node B2.2' },
] },
] },
]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<parent :trees="trees"></parent>
</div>