要对el-form里面的字段动态生成校验规则,测试了一系列的骚操作也无法生效,要么是require视图生效了,校验规则还是不生效;看了csdn里面好多方案,都是废话,废话,直接上硬货,最终总结如下:
<el-form :rules="rules" ref="auditForm" :model="auditForm" label-width="100px">
<el-form-item label="审核结果:" prop="auditStatus">
<el-radio-group v-model="auditForm.auditStatus" @change="updateFormRules">
<el-radio label="Y">通过</el-radio>
<el-radio label="N">不通过</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="审核意见:" prop="remark">
<el-input
v-model="auditForm.remark"
placeholder="请输入"
type="textarea"
:rows="2"
clearable
maxlength="200"
show-word-limit
/>
</el-form-item>
</el-form>
原本的rules里面不必去填写
审核意见
的校验
rules: {
auditStatus: [{ required: true, message: '请选择', trigger: 'blur' }]
},
方案一:监听审核结果的
change
事件,去动态增加审核意见的规则
方案二:使用watch去监听审核结果的值,去动态增加审核意见的规则
updateFormRules () {
if (this.auditForm.auditStatus === 'N') {
this.$set(this.rules, 'remark', [
{ required: true, message: '请输入审核意见', trigger: 'blur' },
{ min: 3, max: 200, message: '长度在 3 到 200 个字符', trigger: 'blur' }
]);
} else {
this.$set(this.rules, 'remark', []);
}
this.$nextTick(() => {
this.$refs.auditForm.clearValidate(); // 清除表单验证规则
this.$refs.auditForm.validate(); // 重新验证表单
});
},```