o1n3n21
o1n3n21

Reputation: 364

Vue.js v-for nested in Table

Probably a basic one, but I've been struggling for a while. I'm trying to create a Table component in Vue 2, populated by data using v-for.

I'd like it to be:
Head1 Head2 Head3 Head4
1 2 3 4
11 22 33 44

My best attempt:

  <table class="timeline-table">
  <thead>
    <tr v-for="(row, key, v) in rows">
      <th>{{ key }}</th>
      <th>{{ key }}</th>
      <th>{{ key }}</th>
      <th>{{ key }}</th>
    </tr>
  </thead>
    <tbody v-for="row in rows">
      <tr>
        <td>{{ row.Head1 }}</td>
        <td>{{ row.Head2 }}</td>
        <td>{{ row.Head3 }}</td>
        <td>{{ row.Head4 }}</td>
      </tr>
    </tbody>
  </table>

With Data structure as:

  rows: [{
    Head1: '1',
    Head2: '2',
    Head3: '3',
    Head4: '4'
  },
  {
    Head1: '11',
    Head2: '22',
    Head3: '33',
    Head4: '44'
  }]

Have tried various, such as rows[0], and nesting the v-for into a r in row, but no success.

Many thanks!

Upvotes: 1

Views: 5734

Answers (1)

akuiper
akuiper

Reputation: 214957

In the header, you need v-for on th instead of tr, also you need to loop through keys in one row to create the header instead of loop through rows:

<table class="timeline-table" id="my-table">
  <thead>
    <tr>
      <th v-for="key in Object.keys(rows[0])">{{ key }}</th>
    </tr>
  </thead>
  <tbody v-for="row in rows">
    <tr>
      <td v-for="key in Object.keys(row)">{{ row[key] }}</td>
    </tr>
  </tbody>
</table>

See the fiddle here.

Upvotes: 3

Related Questions