<template>
<el-form :model="addInfo"
size="mini"
:rules="rules"
ref="addInfo">
<el-form-item label="名称"
prop="title">
<el-input v-model="addInfo.title" size="mini"/>
</el-form-item>
<div v-for="(item, index) in addInfo.userList" :key="index">
<el-form-item label="账号:"
:prop="'userList.'+ index +'.name'"
:rules="rules.username">
<el-input v-model="item.username"
size="mini"/>
</el-form-item>
<el-form-item label="密码:"
:prop="'userList.'+ index +'.password'"
:rules="rules.password">
<el-input v-model="item.password"
type="password"/>
</el-form-item>
<el-form-item label="手机号:"
:prop="'userList.'+ index +'.phone'"
:rules="rules.phone">
<el-input v-model="item.phone"
size="mini"/>
</el-form-item>
</div>
</el-form>
</template>
<script>
export default {
data(){
return {
rules: {
name: [{
required: true,
message: '请输入名称',
trigger: 'blur'}],
phone: [{
required: true,
message: '请输入账号手机号',
trigger: 'blur'}],
username: [{
required: true,
message: '请输入账号名称',
trigger: 'blur'}],
password: [{
required: true,
message: '请输入密码',
trigger: 'blur'}
]
}, // 添加校验
addInfo: {
name: '',
userList: [
{
phone: '',
username: '',
password: ''
},
{
phone: '',
username: '',
password: ''
},
]
}
}
},
methods: {
submitForm(formName) {
alert(formName)
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
</script>
需要注意的是,这个对值的验证是在prop中的,需要对prop改成:prop,值为验证的数据,v-model只是对数据进行存储
例如:
<el-form-item label="密码:"
:prop="'userList.'+ index +'.password'"
:rules="rules.password">
<el-input v-model="item.password"
type="password"/>
</el-form-item>
其中:prop后面的值就是需要进行验证的,同时这个验证和验证规则需要放在el-form-item中,对于非循环出来数据的验证,直接prop绑定即可