先看示例代码,代码为模拟动态获取表单数据,然后动态添加rules验证规则,示例表单内输入框绑定form内第四层:
<template>
<el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item
:label="'name'+index"
v-for="(item,index) in 5"
:key="index"
:prop="'name' + index"
>
<el-input v-model="form.data.top.nameList['name'+index]"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">立即创建</el-button>
</el-form-item>
</el-form>
</template>
<script>
export default {
data() {
return {
form: {
data: {
top: {
nameList: {}
}
}
},
rules: {}
};
},
created() {
for (let i = 0; i < 5; i++) {
this.rules["name" + i] = [
{ required: true, message: "请输入活动名称", trigger: "blur" },
{ min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
];
}
},
methods: {
submitForm() {
console.log(this.rules)
console.log(this.form)
this.$refs.ruleForm.validate(valid => {
if (valid) {
console.log('验证通过');
} else {
return false;
}
});
}
}
};
</script>
效果如下:
可以看到验证规则已经绑定到了输入框,但验证规则却是失效的
点一下按钮看看表单内容和rules的内容,像是没问题的
想要实现验证,需要修改标签内prop属性与rules内属性名。改动如下
:prop="'name' + index" //原
:prop="'data.top.nameList.name' + index" //改后
this.rules["name" + i] = [
{ required: true, message: "请输入活动名称", trigger: "blur" },
{ min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
]; //原
this.rules["data.top.nameList.name" + i] = [
{ required: true, message: "请输入活动名称", trigger: "blur" },
{ min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
]; //改后
全部代码如下:
<template>
<el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item
:label="'name'+index"
v-for="(item,index) in 5"
:key="index"
:prop="'data.top.nameList.name' + index" //修改了这里
>
<el-input v-model="form.data.top.nameList['name'+index]"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">立即创建</el-button>
</el-form-item>
</el-form>
</template>
<script>
export default {
data() {
return {
form: {
data: {
top: {
nameList: {}
}
}
},
rules: {}
};
},
created() {
for (let i = 0; i < 5; i++) {
this.rules["data.top.nameList.name" + i] = [ //修改了这里
{ required: true, message: "请输入活动名称", trigger: "blur" },
{ min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
];
}
},
methods: {
submitForm() {
console.log(this.rules)
console.log(this.form)
this.$refs.ruleForm.validate(valid => {
if (valid) {
console.log('验证通过');
} else {
return false;
}
});
}
}
};
</script>
看一看功能:
点击按钮看一下表单和rules的内容:
总结:将prop绑定为form对象下直到要验证的数据,rules中属性名保证和prop相同。