一、要实现的效果
element 表单提取成公共组件,prop 字段是动态的,双向绑定的值也是动态的,这时候想要添加动态表单校验
1661302886833.png
二、 实现办法
1、静态的表单校验,在<el-form> 标签上添加rules,并定义校验规则,如一下代码所示:
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="活动名称" prop="name">
<el-input v-model="ruleForm.name"></el-input>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
ruleForm: {
name: '',
},
rules: {
name: [
{ required: true, message: '请输入活动名称', trigger: 'blur' },
{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
]
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
2、动态规则校验,在<el-form-item> 标签上添加rules 规则校验,代码如下:
<el-form :model="publishFrom" ref="publishFrom" label-width="100px">
<el-form-item class="w700" :label="`${publishTitle}标题`" :prop="options.title" :rules="{ required: true, message: `请输入${publishTitle}标题`, trigger: 'blur' }">
<el-input v-model="publishFrom[options.title]"></el-input>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
props: {
formData: { // 表单数据
type: Object,
default: () => {}
},
publishTitle: {
type: String,
default: () => '发布'
},
defaultProps: { // 表单配置项
type: Object,
default: () => {}
},
},
watch: {
defaultProps: { // 表单配置项
deep: true,
handler: function (val) {
this.options = { ...this.options, ...val }
}
},
},
data () {
return {
publishFrom: {
id: null, //唯一标识
title: '', // 标题
},
options: { // 表单配置项
id: 'id', // 唯一标识
title: 'title', // 标题
}
}
},
created () {
this.options = { ...this.options, ...this.defaultProps }
},
methods: {
}
}
</script>
网友评论