模板部分,使用 <el-table> 元素作为表格容器,绑定 data 属性传入表格数据。用 v-for 指令遍历每一项数据,使用普通文本或 <el-input> 组件渲染每个单元格。表格最后一列为操作列,包含 “Add” 和 “Delete” 两个按钮,点击它们可以增加或删除数据行:

<template>
  <div>
    <el-table :data="tableData">
      <el-table-column label="Name" prop="name">
        <template #default="{row}">
          <el-input v-model="row.name" />
        </template>
      </el-table-column>
      <el-table-column label="Age" prop="age">
        <template #default="{row}">
          <el-input v-model.number="row.age" type="number" />
        </template>
      </el-table-column>
      <el-table-column label="Actions">
        <template #default="{row}">
          <el-button @click="addRow(row)">Add</el-button>
          <el-button @click="deleteRow(row)">Delete</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

逻辑部分,定义 tableData 数据数组,并分别实现 addRowdeleteRow 两个方法,以响应用户的添加、删除操作。在 addRow 方法中,向 tableData 数组中添加一个空对象。在 deleteRow 方法中,通过 Array.prototype.findIndex() 找到要删除的行在数组中的索引,并使用 Array.prototype.splice() 方法从数组中删除该行:

在这里,我们仍然使用了 ref 函数将 tableData 声明为响应式数据。然后在 template 中调用 addRowdeleteRow 方法,并传入当前操作的行数据作为参数。

希望这能帮到您!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。