vue3+ts实现二维数组的增删改查

356 阅读1分钟
// Table.vue

<template>
  <div>
    <table>
      <thead>
        <tr>
          <th v-for="header in headers" :key="header">{{ header }}</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(row, index) in tableData" :key="index">
          <td v-for="(cell, cellIndex) in row" :key="cellIndex">
            <input v-model="row[cellIndex]" />
          </td>
          <td>
            <button @click="deleteRow(index)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
    <button @click="addRow">添加行</button>
  </div>
</template>

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

export default defineComponent({
  name: 'Table',
  setup() {
    const headers = ref(['列1', '列2', '列3']);
    const tableData = ref([
      ['数据1', '数据2', '数据3'],
      ['数据4', '数据5', '数据6'],
    ]);

    const deleteRow = (index: number) => {
      tableData.value.splice(index, 1);
    };

    const addRow = () => {
      const newRow = headers.value.map(() => '');
      tableData.value.push(newRow);
    };

    return {
      headers,
      tableData,
      deleteRow,
      addRow,
    };
  },
});
</script>

使用Vue的defineComponent函数来定义一个名为Table的组件。在setup函数中,使用ref函数来创建headerstableData这两个响应式数据。

headers存储了表格的列标题,tableData存储了表格的数据。使用v-for指令来循环渲染表格的每一行和每一个单元格,并使用v-model指令来实现数据的双向绑定。

删除行的功能通过deleteRow函数实现,该函数接收一个索引参数,使用splice方法从tableData中删除对应的行数据。

添加行的功能通过addRow函数实现,该函数会根据headers的长度创建一个新的空行,并将其添加到tableData中。

最后,在模板中使用@click指令来绑定删除按钮和添加按钮的点击事件。