So I'm using vue.js in my project and I've got a question: how could I display elements of v-for inside of another v-for as list items or select options? I have abstractly something like:
<div v-for='item in items'>
<div v-for='element in item.elements'>
...
</div>
</div>
Would highly appreciate any possible help, thanks!
v-for. We can use the v-for directive to render a list of items based on an array. The v-for directive requires a special syntax in the form of item in items , where items is the source data array and item is an alias for the array element being iterated on: js const items = ref([{ message: 'Foo' }, { message: 'Bar' } ...
The purpose of this key attribute is to give "a hint for Vue's virtual DOM algorithm to identify VNodes when diffing the new list of nodes against the old list" (from Vue. js Docs). Essentially, it helps Vue identify what's changed and what hasn't.
v-for is most commonly used to render items in a list, but can also be used to iterate over an object's properties or even a set range. When iterating over an array, Vue v-for loops look like this. In this article, we'll be covering some ways to make your v-for loops more precise, predictable, and efficient.
You can use a <template>
tag so as not to render an extra div.
<ul>
<template v-for='item in items'>
<li v-for='element in item.elements'>
{{element.title}}
</li>
</template>
</ul>
<template>
tag is not supported in IE however. A universal solution would be to make a computed variable that returns all of the titles:
computed:{
titles:function(){
var titles = [];
for(var i = 0; i < this.items.length; i++){
for(var k = 0; k < this.items[i].length; k++){
titles.push(this.items[i][k].title);
}
}
return titles;
}
}
Then you can just do v-for="title in titles"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With