【Vue/element】 el-table实现表格动态新增/插入/删除 表格行,可编辑单元格

el-table实现表格动态新增/插入/删除 表格行,可编辑单元格

效果如下:

  • 点击“新增一行”可以在表格最后新增一行,单元格内容可编辑
    在这里插入图片描述
  • 点击绿色+按钮,可在指定行的后面插入一行
    在这里插入图片描述
  • 点击红色-按钮,可以删除指定行
    在这里插入图片描述
    原理:表格el-table是通过动态循环tableData生成,只要对tableData数组进行增加删除元素,就可以达到效果
    这里用了element的el-table,也可以用原生,道理一样
<template>
  <div class="container">
    <el-button
      type="primary"
      size="mini"
      icon="el-icon-circle-plus-outline"
      @click="addRow"
      style="margin-bottom: 20px"
      >新增一行</el-button
    >
    <el-table :data="tableData" border>
      <el-table-column
        label="序号"
        align="center"
        type="index"
        fixed
        sortable
      />

      <el-table-column label="列1" prop="colcumn1" align="center">
        <template slot-scope="scope">
          <div class="flex align-center">
            <el-input v-model="scope.row.colcumn1" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="列2" prop="colcumn1" align="center">
        <template slot-scope="scope">
          <div class="flex align-center">
            <el-input v-model="scope.row.colcumn2" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="success"
            icon="el-icon-plus"
            circle
            size="small"
            @click="addRowIndex(scope.$index)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-minus"
            circle
            size="small"
            @click="delRow(scope.$index)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
      
      
  name: "test",

  data() {
      
      
    return {
      
      
      tableData: [],
    };
  },

  mounted() {
      
      },

  methods: {
      
      
    // 增加一行
    addRow() {
      
      
      const row = {
      
      
        colcumn1: "",
        colcumn2: "",
      };
      this.tableData.push(row);
    },
    // 删除指定行
    delRow(index) {
      
      
      this.tableData.splice(index, 1);
    },
    // 指定位置插入行
    addRowIndex(index) {
      
      
      const row = {
      
      
        colcumn1: "",
        colcumn2: "",
      };
      this.tableData.splice(index + 1, 0, row);
    },
  },
};
</script>

<style scoped>
.container {
      
      
  padding: 50px;
}
</style>

猜你喜欢

转载自blog.csdn.net/qq_23073811/article/details/131188338