vue3 写一个动态新增一行的提交表格使用el-table组件
时间: 2024-09-11 16:08:18 浏览: 209
在Vue3中,我们可以利用Element UI库的`el-table`组件以及其丰富的API来创建一个动态添加新行并提交表单的功能。以下是一个简单的例子:
首先,安装Element UI依赖:
```bash
npm install element-ui
```
然后,在组件中引入相关模块:
```javascript
import { ElForm, ElFormItem } from 'element-plus';
import { defineComponent, ref } from 'vue';
```
接下来,创建一个Vue组件,并实现数据绑定和动态增删行功能:
```html
<template>
<div>
<el-form :model="form" @submit.prevent="submit">
<table>
<thead>
<tr>
<!-- 表头列 -->
<th v-for="(header, index) in headers" :key="index">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in rows track-by:rowIndex">
<td>{{ row[index] || '' }}</td> <!-- 使用row的索引来获取对应的数据项 -->
<td><input type="text" v-model="rows[rowIndex][index]" /></td> <!-- 动态生成输入框,双向绑定数据 -->
<td>
<button @click="removeRow(rowIndex)">删除</button>
</td>
</tr>
<tr>
<td><input type="text" v-model="newRow[index]" placeholder="请输入..." /></td>
<td><button @click="addRow">添加行</button></td>
<td> </td>
</tr>
</tbody>
</table>
</el-form>
</div>
</template>
<script setup>
const headers = ['Header1', 'Header2', 'Action']; // 表格列头
const form = ref({}); // 表单模型
const newRow = ref([]); // 存储新行数据
const rows = ref([]);
// 添加新行函数
function addRow() {
const newRowItem = [...headers, ...newRow.value];
rows.value.push(newRowItem);
newRow.value = [];
}
// 删除指定行
function removeRow(rowIndex) {
rows.value.splice(rowIndex, 1);
}
</script>
```
在这个例子中,我们初始化了两部分数据:静态的表头`headers`和动态的行数据`rows`。当点击“添加行”按钮时,会将新输入的数据追加到当前行;点击“删除”按钮则从数组中移除该行。
记得在`setup`中导入Vue的`ref`来管理状态,`@submit.prevent="submit"`用于阻止默认的表单提交事件,自定义处理表单提交。
阅读全文
相关推荐

















