Winchester
Winchester

Reputation: 490

Vue.js Rendering table with multiple tbody

Basically I have five objects in an array, in every object, there is an attribute called isLastRow with boolean value. I want to have a table with multiple tbody tag, when the item.isLastRow is true, the next index would create new tbody with tr. Obviously, my current attempt just iterates the items and render five tbody, the expect result would be just two tbody. The first tbody will have two tr and the last tbody has three tr.

let items = [
    {
        id: 0,
        text: a,
        isLastRow: false,
    },
    {
        id: 1,
        text: a,
        isLastRow: true,
    },
    {
        id: 2,
        text: b,
        isLastRow: false,
    },
    {
        id: 3,
        text: b,
        isLastRow: false,
    },
    {
        id: 4,
        text: b,
        isLastRow: true,
    },
]



<template v-for="item in items">
  <tbody :key="item.id">
    <tr>
        <td>
            {{ item.text }}
        </td>
    </tr>
  </tbody>
</template> 

This is the result I expect to be

<table>
    <tbody>
        <tr>
            <td rowspan="2"></td>
            <td>a</td>
        </tr>
        <tr>
            <td>a</td>
        </tr>
    </tbody>
        <tbody>
        <tr>
            <td rowspan="3"></td>
            <td>b</td>
        </tr>
        <tr>
            <td>b</td>
        </tr>
        <tr>
            <td>b</td>
        </tr>
    </tbody>

</table> 

Upvotes: 0

Views: 538

Answers (1)

JaredMcAteer
JaredMcAteer

Reputation: 22536

You are going to have to use a computed property to format your data structure to be something like

[
  [
    { id: 0, text: a, isLastRow: false },
    { id: 1, text: a, isLastRow: true },
  ],
  [
    { id: 2, text: b, isLastRow: false },
    { id: 3, text: b, isLastRow: false },
    { id: 4, text: b, isLastRow: true },
  ],
]; 

e.g.,

computed: {
  getFormatedItems() {
    const sections = [[]];
    let index = 0;

    this.items.forEach(item => {
      if (item.lastRow) {
         index++;
         section[index] = [];
      }
      section[index].push(item);
    });
  },
},

Then you can write you template like

<template v-for="(section, index) in getFormatedItems">
  <tbody :key="index">
    <tr v-for="item in section" :key="item.id">
      <td>{{item.text}}</td>
    </tr>
  </tbody>
</template>

Upvotes: 1

Related Questions