I’m looking at the example on Vue.js documentation for iteratively rendering a Tree using the v-for directive. My goal was to alter the code to iteratively render multiple TreeItems in the App.vue file.
My question is why can you iteratively render TreeItem by passing down a list of children objects in the ‘TreeItem.vue’ file, but when trying to iteratively render TreeItem in App.vue, it does not render multiple tree objects within a list. Reading over the docs, the v-for mentions it renders ‘element or template block’ but seems inconsistent with how it’s being called in ‘TreeItem.vue’.
Any explanation to help my understanding is greatly appreciated!
Link to original code example: https://vuejs.org/examples/#tree
I was getting stuck trying use v-for within the TreeItem component like so:
const listOfTrees = ref([{
name: 'My Tree 2',
children: [
{ name: 'hello' },
{ name: 'world' },
{
name: 'child folder',
children: [
{
name: 'child folder',
children: [{ name: 'hello' }, { name: 'world' }]
},
]
}
]
},{
name: 'My Tree',
children: [
{ name: 'hello' },
{ name: 'world' },
{
name: 'child folder',
children: [
{
name: 'child folder',
children: [{ name: 'hello' }, { name: 'world' }]
},
{ name: 'hello' },
{ name: 'world' },
{
name: 'child folder',
children: [{ name: 'hello' }, { name: 'world' }]
}
]
}
]
}
])
<template>
<ul>
<TreeItem class="item" f-for="tree in listOfTrees" :model="treeData"></TreeItem>
</ul>
</template>
I did get something to work where I wrapped the ‘outer’ ul in a div and iteratively rendered the div’s:
<template>
<!-- Wrapped the entire ul in a div and iterate the div's -->
<div v-for= "tree in listOfTrees">
<ul>
<TreeItem class="item" :model="tree"></TreeItem>
</ul>
</div>
</template>
This result was what I was expecting during the first approach. I’m curious as to why the second attempt was successful and the first was not.
2
Answers
Hmmm. first of all there is a typeo, so
f-for
should bev-for
.Also, template goes like this:
So, iteration goes like this on vue.
Don’t hesitate if you need more explanation.