Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue.js double v-for in list

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!

like image 980
Coffee Avatar asked Apr 18 '16 06:04

Coffee


People also ask

What is V-for in Vue?

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' } ...

What is key in V-for?

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.

Where do we use V?

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.


1 Answers

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"

like image 76
Jeff Avatar answered Sep 19 '22 15:09

Jeff