[Vuejs]-Dynamically create html table from an Array

0👍

You need to specify both the columns that should be rendered, as well as the rows with all data.

The Table.vue could look like this:

<template>
  <table>
    <thead>
      <tr>
        <th v-for="(column, index) in columns" :key="index">
          {{ column }}
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(row, index) in rows" :key="index">
        <td v-for="(column, index) in columns" :key="index">
          {{ row[column] }}
        </td>
      </tr>
    </tbody>
  </table>
</template>

<script>
export default {
  name: "Table",
  props: {
    columns: Array,
    rows: Array,
  },
};
</script>

…and the parent component would then pass the data into Table.vue like this:

<template>
  <Table :columns="columns" :rows="rows" />
</template>

<script>
import Table from "./components/Table";

export default {
  name: "App",
  components: {
    Table,
  },
  data() {
    return {
      columns: ["id", "title", "description"],
      rows: [
        {
          id: 1,
          title: "what is this",
          description: "i like to describe",
        },
        {
          id: 2,
          title: "wait wat?",
          description: "i like to describe, too",
        },
      ],
    };
  },
};
</script>

See the working codesandbox.

Note that most actual Vue dataTable components use render functions for performance reasons.

Leave a comment