在实际使用中经常会遇到需要在From表单中使用table表格进行表单提交,同时又需要对From表单中的字段进行校验,效果如图所示:
这个校验中,最关键的问题在于如何给el-form-item 动态绑定prop
<template>
<div class="app-container">
<div class="filter-container">
<el-button type="primary" @click="init()" icon="el-icon-circle-plus">add</el-button>
</div>
<el-dialog title="表单Table" :visible.sync="dialogFormVisible">
<el-form :model="fromData" ref="from">
<el-table :data="fromData.quickedData">
<el-table-column label="姓名">
<template slot-scope="scope">
<el-form-item :prop="'quickedData.'+scope.$index+'.name'" :rules="fromaDataRules.name">
<el-input v-model="scope.row.name"></el-input>
</el-form-item>
</template>
</el-table-column>
<el-table-column label="地址">
<template slot-scope="scope">
<el-form-item :prop="'domains.'+scope.$index+'.desc'" :rules="fromaDataRules.desc">
<el-input v-model="scope.row.desc"></el-input>
</el-form-item>
</template>
</el-table-column>
</el-table>
</el-form>
<el-button type="warning" @click="submit('from')">submit</el-button>
</el-dialog>
</div>
</template>
<script>
export default {
data() {
return {
dialogFormVisible:false,
fromData:{
quickedData:[]
},
fromaDataRules:{
name:[{ required: true, message: '请输入活动名称', trigger: 'blur' }],
desc:[ { required: true, message: '请填写活动形式', trigger: 'blur' }]
},
}
},
mounted(){
this.initDomains()
},
methods:{
initDomains(){
this.domains=[
{
name: undefined,
desc: undefined
},
{
name:undefined,
desc:undefined
}
]
},
init(){
this.dialogFormVisible = true
this.$set(this.fromData,'quickedData',this.quickedData)
},
async submit(formName){
//多表单验证
try {
await Promise.all([
this.$refs.addFormRef.validate()
// this.$refs.levelFormRef.validate()
]);
} catch (error) {
return this.$message.error('请填写完整!');
}
}
}
}
</script>
上述代码中比较关键的部分有一下两点:
1、:prop="‘quickedData.’+scope.$index+’.name’" ,用于动态绑定prop到el-form-item;
2、this.$set(this.fromData,‘quickedData’,this.quickedData) ,用于为fromData设置quickedData这个节点。