generate n x m table in vue in typescript

To generate an n x m table in Vue using TypeScript, you can follow these steps:

  1. Define the table data in your component's data property. Here, we'll use a two-dimensional array to represent the table:
index.ts
data() {
  return {
    tableData: Array(n).fill(0).map(() => Array(m).fill(0))
  }
}
86 chars
6 lines
  1. Generate the table rows and columns using v-for directives in your template:
<table>
  <tbody>
    <tr v-for="(row, i) in tableData" :key="i">
      <td v-for="(cell, j) in row" :key="j">{{ cell }}</td>
    </tr>
  </tbody>
</table>
156 chars
8 lines
  1. Optionally, you can add input fields to allow users to edit the table:
<table>
  <tbody>
    <tr v-for="(row, i) in tableData" :key="i">
      <td v-for="(cell, j) in row" :key="j">
        <input type="number" v-model.number="tableData[i][j]">
      </td>
    </tr>
  </tbody>
</table>
216 chars
10 lines
  1. You can also add additional logic to your component to manipulate the table data, such as adding or removing rows and columns.

Here's a complete example of a Vue component to generate a 3 x 3 table in TypeScript:

index.ts
<template>
  <div>
    <table>
      <tbody>
        <tr v-for="(row, i) in tableData" :key="i">
          <td v-for="(cell, j) in row" :key="j">
            <input type="number" v-model.number="tableData[i][j]">
          </td>
        </tr>
      </tbody>
    </table>
    <button @click="addRow">Add Row</button>
    <button @click="addColumn">Add Column</button>
  </div>
</template>

<script lang="ts">
  import { Vue, Component } from 'vue-property-decorator'

  @Component
  export default class TableComponent extends Vue {
    private n = 3
    private m = 3
    private tableData: number[][] = Array(this.n).fill(0).map(() => Array(this.m).fill(0))

    private addRow(): void {
      this.tableData.push(Array(this.m).fill(0))
    }

    private addColumn(): void {
      this.tableData.forEach(row => row.push(0))
      this.m++
    }
  }
</script>
861 chars
36 lines

gistlibby LogSnag