vue3 table in typescript

Here's an example implementation of a Vue3 table component using TypeScript and the Composition API:

<template>
  <table>
    <thead>
      <tr>
        <!-- Use v-for to loop through columns -->
        <th v-for="column in columns" :key="column.field">{{ column.title }}</th>
      </tr>
    </thead>
    <tbody>
      <!-- Use v-for to loop through rows -->
      <tr v-for="row in rows" :key="row.id">
        <!-- Use v-for to loop through columns and render cell data -->
        <td v-for="column in columns" :key="column.field">
          {{ row[column.field] }}
        </td>
      </tr>
    </tbody>
  </table>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue';

interface Column {
  title: string;
  field: string;
}

interface Row {
  [key: string]: any;
}

export default defineComponent({
  name: 'Table',
  props: {
    columns: {
      type: Array as PropType<Column[]>,
      required: true,
    },
    rows: {
      type: Array as PropType<Row[]>,
      required: true,
    },
  },
});
</script>
943 chars
47 lines

In this example, we define a Table component that accepts two props: columns and rows. The columns prop is an array of objects that define the columns of the table, while the rows prop is an array of objects that define the data for each row.

We then use v-for loops to render the table headers and cells. We loop through the columns prop to render the table headers, and then loop through the rows prop to render the table cells by accessing the data via the column keys.

gistlibby LogSnag