Home > front end >  Using v-for in a table
Using v-for in a table

Time:11-19

I have a table is populated with some info and I would like to format the table like the picture

Table Unfortunately the excel sheet which I have no control over is formatted so:

Spread Sheet

I want any row that has only a Equipment type to span whole row. All other rows should appear as normal table row.

I am using following vue template:

<table>
    <caption>
      SHS Scrap Table
    </caption>
    <thead>
      <tr>
        <th>Make</th>
        <th>Model #</th>
        <th>Bar Code</th>
        <th>Serial #</th>
        <th>Location</th>
        <th>Condition</th>
      </tr>
    </thead>
    <tbody v-for="item in scrapDataEmptyRowsRemoved" :key="item">
      <tr v-if="item['Equipment Type']">
        <td  colspan="6">
          Equipment Type - {{ item["Equipment Type"] }}
        </td>
      </tr>
      <tr v-else>
        <td>{{ item["Make"] }}</td>
        <td>{{ item["Model #"] }}</td>
        <td>{{ item["Bar Code"] }}</td>
        <td>{{ item["Serial #"] }}</td>
        <td>{{ item["Location"] }}</td>
        <td>{{ item["Condition"] }}</td>
      </tr>
    </tbody>
  </table>

Dom

The only problem is that looking in Devtools I see that every row has a Tbody which is not semantically correct. Any idea's on how to correct this. If I use a container around the v-if v-else all formatting breaks down.Thanks...

Update the only problem is Vite is objecting to moving :key attribute to the v-else:

Vite error

I dont what other unique key they want.

Update II - Ok apparently if I use different object keys Vite is ok with that ie :key="item['Equipment Type'] and on v-else :key="item['Make']. Does that seem correct?

CodePudding user response:

You can move the v-for in a template tag, that won't be rendered in the DOM.

<tbody>
  <template  v-for="item in scrapDataEmptyRowsRemoved" :key="item">
    <tr v-if="item['Equipment Type']">
      <td  colspan="6">
        Equipment Type - {{ item["Equipment Type"] }}
      </td>
    </tr>
    <tr v-else>
      <td>{{ item["Make"] }}</td>
      <td>{{ item["Model #"] }}</td>
      <td>{{ item["Bar Code"] }}</td>
      <td>{{ item["Serial #"] }}</td>
      <td>{{ item["Location"] }}</td>
      <td>{{ item["Condition"] }}</td>
    </tr>
  </template>
</tbody>
  • Related