[Vuejs]-Iterating over multiple table rows with v-for

3👍

Rather than trying to reshape the template to fit the data, you may be able to reshape the data to fit the template. Here’s an example where the collection is split into an array of rows so that a simple v-for can be used with <td> elements:

<template>
  <tbody>
    <tr v-for="(item, index) in rows" :key="index">
      <td>{{ item.column1 }}</td>
      <td>{{ item.column2 }}</td>
    </tr>
  </tbody>
</template>
const ITEMS = [
  { foo: 'a1', bar: 'a2', foo2: 'b1', bar2: 'b2' },
  { foo: 'c1', bar: 'c1', foo2: 'd2', bar2: 'd2' },
];

export default {
  data() {
    return { items: ITEMS };
  },
  computed: {
    rows() {
      const result = [];
      this.items.forEach(({ foo, bar, foo2, bar2 }) => {
        result.push({ column1: foo, column2: bar });
        result.push({ column1: foo2, column2: bar2 });
      });
      return result;
    },
  },
};

Leave a comment