我们组长说我这样写的不对,让我想想怎么写更好,我这个脑子呀,想了半天没想明白。。。。因为这个是非必填项,所以我没有在rule来做,前辈们换你们的话会怎么写好?

onSaveComp() {
this.$refs.compForm.validate((valid) => {
if (valid) {
let params = {};
if (this.compForm.target != '' && !this.isURL(this.compForm.target)) {
this.$message.error('输入的跳转地址不正确!');
return false;
}
if (this.compForm.type == 'DATASOURCE') {
this.compForm.modes = this.compForm.modes.replace(/-/g, '').toUpperCase();
params = {
...this.compForm,
style: '',
};
} else {
params = {
appId: this.compForm.appId,
exts: '',
name: this.compForm.name,
nameEn: this.compForm.nameEn,
url: this.compForm.url,
type: 'IFRAME',
roleIds: this.compForm.roleIds,
status: this.compForm.status,
thumbnail: this.compForm.thumbnail,
target: this.compForm.target,
};
}
createComp(params).then(() => {
this.$message.success('创建成功');
parent.history.back();
});
}
});
},
“不对”是指写的位置不对?做法不对?代码不对?还是其他什么不对?
不清楚业务,也不清楚结构,所以只说说代码
isURL
有没有兼容 ""
的情况?如果有,那第 1 个条件就可省略。
另外,target 是否有可能是 undefined?如果有可能,要看 isURL
是否会处理,不会就需要加判断。不过我觉得 isURL 作为工作函数,目的就是减少代码量,应该充分考虑这些日常情况。
另外 if (valid)
贯穿了整个 Lambda,可以直接使用反向条件提前结束函数,减少缩进层次

下面 else 中对 params 的赋值也可以参考上面的 ...this.comForm
,不用一个个去(前提是 comForm 中可能存在的多余属性不会产生副作用)

“不对”是指写的位置不对?做法不对?代码不对?还是其他什么不对?
不清楚业务,也不清楚结构,所以只说说代码
isURL
有没有兼容 ""
的情况?如果有,那第 1 个条件就可省略。
另外,target 是否有可能是 undefined?如果有可能,要看 isURL
是否会处理,不会就需要加判断。不过我觉得 isURL 作为工作函数,目的就是减少代码量,应该充分考虑这些日常情况。
另外 if (valid)
贯穿了整个 Lambda,可以直接使用反向条件提前结束函数,减少缩进层次

下面 else 中对 params 的赋值也可以参考上面的 ...this.comForm
,不用一个个去(前提是 comForm 中可能存在的多余属性不会产生副作用)

说不上不好,添加更多的验证就更好了
if(typeof this.comForm.target !== 'string'){
return false;
}
const target = this.comForm.target.trim()
if(target === ''){
return false;
}
if(!this.isURL(target)){
return false;
}
this.compForm.target && !this.isURL(this.compForm.target)
或者
!this.isURL(this.compForm.target) + 在isURL方法里做判断
可以通过动态调整rules中required属性来达到你所说的效果,required设置为false就OK了
非必填的正则验证。这里是常用的URL验证,那么可以写成指令v-,或封装成方法,方便后面复用
PS:写在这里确实会影响代码美观
应该是指让你按照element-ui的form最佳实践来吧,而不是验证后,再去验证。。。
看见大家都好强啊,估计我是最懒的一个。我都是让后台配好json,一个接口表单规则就出来了。理由是用户可以自行配置表单。前后端分离最累的是前端,能用组件就用组件,减少自己打代码。
http://form-create.com/

1、在el-form-item标签上写
<el-form-item prop="yearPriceRate"></el-form-item>
2、在rules中定义:
yearPriceRate: [
{
validator: (rule, value, callback) => {
if (!value) {
return callback();
} else {
if (+value > 100) {
callback(new Error("比例不能超过100%"));
} else if (+value <= 0) {
callback(new Error("比例不能小于等于0"));
} else {
return callback();
}
}
},
trigger: "blur",
},
]
表单的验证还是写在rule里,去掉必填属性,点击提交的时候可以调用表单的validateField方法只校验指定字段(prop)
Function(props: array | string, callback: Function(errorMessage: string))
this.$refs.compForm.validateField(['name'], (errorMessage) => {
})