今天遇到一个需要给 for 循环体里面的 form 表单项添加校验的需求,为每一个循环的模块单独添加校验,实现如下:
<el-form
:model="form"
:rules="rules"
ref="form"
label-width="120px"
class="demo-ruleForm">
<el-form-item label="名称" prop="name">
<el-input v-model="form.name" placeholder="填写名称"></el-input>
</el-form-item>
<!--循环体-->
<template v-for="(item,index) in form.list">
<el-form-item label="类型" :prop="`list.${index}.type`" :rules='rules.type'>
<el-input v-model="item.type" placeholder="填写类型"></el-input>
</el-form-item>
<el-form-item label="版本" :prop="`list.${index}.version`" :rules='rules.version'>
<el-select
style="width: 100%;"
v-model="item.version"
placeholder="选择版本"
>
<el-option
v-for="(item,index) in versionList"
:key="index"
:label="item"
:value="item"
></el-option>
</el-select>
</el-form-item>
</template>
</el-form>
<style>
export default {
data(){
return {
versionList:[],
form:{
name:'',
list:[
{
type:'',
version:''
},
{
type:'0',
version:''
},
{
type:'1',
version:''
}
]
},
rules:{
type: [
{
required: true, message: '请填写类型', trigger: 'change' }
],
version: [
{
required: true, message: '请填选择版本', trigger: 'change' }
]
}
}
}
}
</stype>
注意:
1、循环体绑定的 list 必须是 form 里面的对象
2、prop 绑定动态的属性, rules 对动态属性校验
3、prop 绑定的属性名和 rules 绑定的校验名必须保持一致
效果:
转载:https://blog.csdn.net/weixin_43299180/article/details/115721741
查看评论