项目场景:
在实际使用中经常会遇到table表格可编辑提交数据时需要进行相关字段的验证,这种需求很常见,记录很重要。
问题描述
验证输入项 进行提示及阻止下一步操作
解决方案:
表单与表格结合进行验证提交
完整实例代码:
<template>
<div class="page-layout rataMdel">
<el-button type="primary" @click="addItem">+添加一行</el-button>
<el-form
:model="ruleForm"
ref="ruleForm"
label-width="100px"
class="demo-ruleForm"
>
<el-table :data="ruleForm.tableList" style="width: 100%">
<el-table-column prop="name">
<!-- 变量rules -->
<template slot-scope="scope">
<el-form-item
label="活动名称"
:prop="'tableList.' + scope.$index + '.name'"
:rules="rules.name"
>
<el-input v-model="scope.row.name"></el-input>
</el-form-item>
</template>
</el-table-column>
<el-table-column prop="region">
<!-- 行内rules -->
<template slot-scope="scope">
<el-form-item
label="活动区域"
:prop="'tableList.' + scope.$index + '.region'"
:rules="[{ required: true }]"
>
<el-select v-model="scope.row.region" placeholder="活动区域">
<el-option label="区域一" value="shanghai"></el-option>
<el-option label="区域二" value="beijing"></el-option>
</el-select>
</el-form-item>
</template>
</el-table-column>
</el-table>
</el-form>
<div style="margin-top: 20px">
<el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
ruleForm: {
tableList: []
},
rules: {
name: [
{ required: true, message: "请输入活动名称", trigger: "blur" },
{ min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
]
}
};
},
methods: {
addItem() {
this.ruleForm.tableList.push({
name: "",
region: ""
});
},
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert("submit!");
} else {
console.log("error submit!!");
return false;
}
});
}
}
};
</script>
<style rel="stylesheet/scss" lang="scss">
.rataMdel {
.el-table td {
padding: 6px 0;
}
.el-form-item__error {
display: none;
}
.header-flex {
display: flex;
align-items: center;
justify-content: space-between;
}
.tableTitle {
font-size: 20px;
margin-bottom: 30px;
}
.charts-box {
width: 100%;
display: flex;
justify-content: center;
}
.tableText {
padding: 15px;
font-size: 15px;
color: #333333;
}
.small-num {
display: inline-block;
width: 70px;
}
.small-string {
display: inline-block;
width: 130px;
}
p {
margin: 0;
padding: 0;
}
.el-form-item {
display: inline-block;
margin-bottom: 0px;
}
}
</style>
关键代码:
:prop="'tableList.' + scope.$index + '.name'"
注意点:
删除数据时,注意验证规则
效果:
每天记录一点,助力成长!
欢迎大家来浏览我的博客,如发现我有写错的地方,欢迎交流指正。
如果你觉得本文对你有帮助,欢迎点赞收藏转载,烦请注明出处,谢谢!