element el-table实现表格动态增加/删除/编辑表格行,带校验规则
    		       		warning:
    		            这篇文章距离上次修改已过448天,其中的内容可能已经有所变动。
    		        
        		                
                在Vue.js中,可以使用Element UI库中的el-table组件来实现动态增加、删除和编辑表格行的功能。以下是一个简单的示例,展示了如何实现这些功能,并且每次编辑后都会进行验证。
<template>
  <div>
    <el-button @click="addRow">添加行</el-button>
    <el-table :data="tableData" style="width: 100%;">
      <el-table-column prop="date" label="日期" width="180">
        <template slot-scope="scope">
          <el-input v-model="scope.row.date" placeholder="请输入日期"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="180">
        <template slot-scope="scope">
          <el-input v-model="scope.row.name" placeholder="请输入姓名"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button @click="editRow(scope.$index, scope.row)">编辑</el-button>
          <el-button @click="deleteRow(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      tableData: [
        {
          date: '2016-05-02',
          name: '王小虎',
        },
        // ...可以添加更多行
      ],
    };
  },
  methods: {
    addRow() {
      this.tableData.push({ date: '', name: '' });
    },
    editRow(index, row) {
      // 编辑操作,可以在这里添加验证逻辑
    },
    deleteRow(index, row) {
      this.tableData.splice(index, 1);
    },
  },
};
</script>在这个示例中,我们定义了一个tableData数组来存储表格的数据。在模板中,我们使用el-table组件来展示数据,并通过el-table-column定义每列的内容。每个单元格的内容都由一个el-input组件提供,允许用户直接编辑。每行后面的操作列包含两个按钮,分别用于编辑和删除行。
添加行时,我们简单地向tableData数组添加一个新的空对象。编辑行时,可以添加验证逻辑。删除行时,我们使用数组的splice方法来移除指定索引的行。
评论已关闭