Home > Software design >  Vue 2 v-for with multiple items
Vue 2 v-for with multiple items

Time:11-19

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?

CodePudding user response:

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.

CodePudding user response:

In addition to Dmitry's solution, typically, you would want to loop your rows, and use blocks in the same td.

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

or

  <table>
      <tr v-for="item in items">
        <td>
          <div>{{item.line1}}</div>
          <div>{{item.line2}}</div>
        </td>
      </tr>
  </table>
  • Related