vue3结合element-plus实现动态表格,可添加、删除、对单行数据判断。
实现效果:查看源代码
实现代码:
<div class="arrTable-Box">
<el-table :data="tableData" border max-height="250">
<el-table-column prop="name" label="Name">
<template #default="{row}">
<el-input v-model="row.name" clearable />
</template>
</el-table-column>
<el-table-column prop="age" label="Age">
<template #default="{row}">
<el-input v-model="row.age" clearable />
</template>
</el-table-column>
<el-table-column prop="balance" label="Balance">
<template #default="{row}">
<el-input v-model="row.balance" clearable />
</template>
</el-table-column>
<el-table-column fixed="right" label="Operations">
<template #default="scope">
<el-button link type="primary" size="small" v-if="scope.$index!=0" @click.prevent="removeRow(scope.$index)">
Remove
</el-button>
</template>
</el-table-column>
</el-table>
<div class="flex">
<el-button class="w100 mt10" type="danger" @click="addRow"> Add </el-button>
<el-button class="w100 mt10" type="primary" @click="sumbit"> sumbit </el-button>
</div>
</div>
import {ref} from 'vue'
const tableData = ref([{
name: 'Tom',
age: 20,
balance: 100,
},
])
/* 删除行 */
const removeRow = (index) => {
tableData.value.splice(index, 1)
}
/* 新增行 */
const addRow = () => {
tableData.value.push({})
}
/* 判断是否为空对象 */
const isRowEmpty = (row) => Object.keys(row).length === 0;
/* 判断每行数据是否为真 */
const isRowComplete = (row) => row.name && row.age && row.balance;
/* 提交 */
const sumbit = () => {
const data=[...tableData.value];
for (let i = 0; i < data.length; i++) {
const row = data[i];
if (isRowEmpty(row)) {
ElMessage.warning(`请填写第${i + 1}行内容!`);
return;
}
if (!isRowComplete(row)) {
ElMessage.warning(`请将第${i + 1}行内容补充完整`);
return;
}
}
console.log('submit data:',data);
}