Search code examples
vue.jsvuejs2v-for

Vue 2 v-for with multiple items


When trying to fill a table with rows using v-for it is quite easy to map the v-for elements 1:1 with the rows like:

<template>
  <table>
    <tr v-for="item in items"><td>{{item}}</td></tr>
  </table>
</template>

My question is: how can I create multiple rows (eg td elements) per item (see following pseudocode):

<template>
  <table>
    <nothing v-for="item in items">
      <tr><td>{{item.line1}}</td></tr>
      <tr><td>{{item.line2}}</td></tr>
    </nothing>
  </table>
</template>

Here <nothing> should not be emitted in the DOM as a level, only <td> directly under <table>.

Is this possible?


Solution

  • In Vue.js, you can use tag <template>, it does exactly what you meant by nothing.

    <table id="t1">
        <template v-for="item in items">
            <tr><td>{{item.line1}}</td></tr>
            <tr><td>{{item.line2}}</td></tr>
        </template>
    </table>
    

    But alternatively, you can wrap these two lines into tbody tag to actually render it and group the lines in two, e.g., for styling.