1.背景:
使用element-ui的form表单校验功能时,点击提交会对所有要校验的值进行校验,如下图:
虽然提示了要必须填写的值,但是不太美观,产品经理要求点击提交只提示最先校验的那个,如下图
2.方法
使用form表单的这个方法
?然后对必填项进行遍历调用‘
// html
<el-form ref="dataForm" :rules="dataRule"***
// data
dataRule: {
title: [
{ required: true, message: '标题不能为空', trigger: 'blur' }
],
weight: [
{ required: true, message: '权重不能为空', trigger: 'blur' }
],
store: [
{ required: true, message: '适用门店不能为空', trigger: 'blur' }
],
messageOne: [
{ required: true, message: '回复消息1不能为空', trigger: 'blur' }
],
messageTwoImg: [
{ required: true, message: '请添加图片', trigger: 'change' }
],
appletPath: [
{ required: true, message: '小程序路径不能为空', trigger: 'blur' }
],
appletCardTitle: [
{ required: true, message: '卡片标题不能为空', trigger: 'blur' }
],
appletCardCover: [
{ required: true, message: '请添加图片卡片封面', trigger: 'change' }
]
}
// methods
filedCheck(prop) {
let noSave = false
this.$refs.dataForm.validateField(prop, valid => {
if (valid) { // valid返回的是dataRule的message,有值说明触发必填校验,不能提交
noSave = true
}
})
return noSave
},
dataFormSubmit() {
const validateFieldList = Object.keys(this.dataRule)
const noSave = validateFieldList.some(i => this.filedCheck(i))
if (!noSave) {
// 调用保存接口
}
}
|