1

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!

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.