《Vue》聊一聊实际项目中输入框的校验的几种优化方案,HTML标签之表单标签

本文探讨了在Vue项目中针对大量输入框校验的优化方案,包括抽离公共函数简化验证规则和使用自定义指令控制输入合法性。通过实例展示了如何减少重复代码,提高开发效率和用户体验。
摘要由CSDN通过智能技术生成

formValidate: {

name: ‘’,

mail: ‘’,

},

ruleValidate: {

name: [

{ required: true, message: ‘The name cannot be empty’, trigger: ‘blur’ }

],

mail: [

{ required: true, message: ‘Mailbox cannot be empty’, trigger: ‘blur’ },

{ type: ‘email’, message: ‘Incorrect email format’, trigger: ‘blur’ }

]

}

}

}

}

这是官网的例子,裁剪了一部分代码,原版代码太多了,在这次查看的项目中同样发现了大量这种较为基础的用法,这种用法对对于需要在一个界面上放十几个输入框的设计,会存在大量重复rules代码,并且重复的量还特别太夸张,比如,我增见到过一个弹窗,光是输入框就将近15个,写了光是这个ruleValidate就写了100多行…直呼牛皮…

可能有很多小伙伴发现,这种写法中除了message提示的信息不一样,其它配置都是完全一致的,从共性抽离的角度来讲,那不是完全可以抽离?

优化

============================================================

方式一:抽离公共函数


既然是优化,那么首先需要确认的就是可优化点,正如上面所说,经过分析发现,大量输入框的校验只有一种,必输项,换个说法就是这个输入框必须输入,除此之外没有别的限制,但是仅仅这一个需求,最后可能演变的代码就变成了这样:

ruleValidate: {

name: [

{ required: true, message: ‘The name cannot be empty’, trigger: ‘blur’ }

],

mail: [

{ required: true, message: ‘Mailbox cannot be empty’, trigger: ‘blur’ }

],

city: [

{ required: true, message: ‘Please select the city’, trigger: ‘blur’ }

],

gender: [

{ required: true, message: ‘Please select gender’, trigger: ‘blur’ }

],

desc: [

{ required: true, message: ‘Please enter a personal introduction’, trigger: ‘blur’ }

]

}

其实完全没有必要,不同数组之间最大的区别也就是提示的文字不同,我们完全可以抽离一个公共函数来做统一处理,比如,我们期望改完后关于验证是这么写的:

ruleValidate: {

name: Validate(“The name cannot be empty”),

mail: Validate(“Mailbox cannot be empty”),

city: Validate(“Please select the city”),

gender: Validate(“Please select gender”),

desc: Validate(“Please enter a personal introduction”)

}<

  • 30
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值