<template>
<el-form ref="formName" :model="studentData">
<el-table :data="studentData.studentList" stripe>
<el-table-column label="姓名" align="left">
<template slot-scope="scope">
<el-form-item
size="small"
:prop="'studentList.' + scope.$index + '.name'"
:rules="rules.name"
>
<el-input v-model="scope.row.name" placeholder="请输入姓名" />
</el-form-item>
</template>
</el-table-column>
<el-table-column label="性别">
<template slot-scope="scope">
<el-form-item
size="small"
:prop="'studentList.' + scope.$index + '.sex'"
:rules="rules.sex"
>
<el-select v-model="scope.row.sex" placeholder="请选择性别">
<el-option label="男" value="1"></el-option>
<el-option label="女" value="0"></el-option>
</el-select>
</el-form-item>
</template>
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button
type="text"
id="delete-btn"
@click="deleteRow(scope.row, scope.$index)"
>删除</el-button
>
</template>
</el-table-column>
</el-table>
<div style="margin: 20px; text-align: right">
<el-button @click="addRow" size="small">新增</el-button>
<el-button @click="saveData('formName')" size="small">确定</el-button>
</div>
</el-form>
</template>
<script>
export default {
data() {
return {
studentData: {
studentList: [
{
name: "王小虎",
sex: "男",
},
{
name: "Linda",
sex: "女",
},
],
},
//验证规则
rules: {
name: [
{
required: true,
message: "请输入姓名",
trigger: ["blur", "change"],
},
],
sex: [
{
required: true,
message: "请选择性别",
trigger: ["blur", "change"],
},
],
},
};
},
methods: {
// 添加一行
addRow() {
const item = {
name: "",
sex: "",
};
this.studentData.studentList.push(item);
},
// 删除一行
deleteRow(row, index) {
this.studentData.studentList.splice(index, 1);
},
saveData(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert("submit!");
} else {
console.log("error submit!!");
return false;
}
});
},
},
};
</script>
<style scoped>
.el-form {
width: 60%;
background: white;
border: 1px solid gainsboro;
}
/deep/ .el-input {
width: 100%;
}
</style>
点击新增,table新增一行,点击删除,删除所在行。若验证不通过,点击“确定”,提示如下图
- 需要借助el-form的校验,el-table外层嵌套一层el-form,使用el-form的校验机制
- 由于每行都需要校验,借助scope.$index
- 给表单设置rules属性传入验证规则
- 给表单设置model属性传入表单数据
- 给表单项(Form-ltem)设置prop属性,值为需要校验的字段名