if (
!this.customerInfo.customerNumber ||
!this.customerInfo.customerName ||
!this.customerInfo.detailedAddress ||
!this.customerInfo.district ||
!this.customerInfo.typeName
) {
this.$message.error('请填写必填信息')
}
if (this.helpStatus == '客户分类') {
this.typeId = this.selectHelpData.id
this.customerInfo.typeName = this.selectHelpData.typeName
}
if (this.helpStatus == '客户级别') {
this.levelId = this.selectHelpData.id
this.customerInfo.levelName = this.selectHelpData.levelName
}
if (this.helpStatus == '客户区域') {
this.areaId = this.selectHelpData.id
this.customerInfo.areaName = this.selectHelpData.areaName
}
像这种判断输入值和在每个if中写不同逻辑的应该如何优化,感谢各位
第一段没太多可优化的,但是可以考虑使用一个临时变量来引用
this.customerInfo
,或者直接一次把需要判断的所有属性取出来。下面这个示例用了一些花哨的语法:下面那一段的常规写法应该是
switch
,就算要用if
语句,也应该使用else if
,否则可能会有无用的判断(无论哪个条件匹配,都会去判断三个条件)。还有一点,尽量避免使用
==
。写代码时自己要明确数据类型,使用===
不过看起来,各分支代码相似,只有一丁点差别,可以用函数来输入属性名称,
甚至可以更近一步 —— 因为属性名除了前缀都一样:
这样的封装在分支代码较长的时候看起来会比较有用。不过都封成这样了,不妨再用 map 改进一下
这样看起来并没减少多少麻烦,但是维护起来会更方便,比如业务逻辑发生变化的时候只需要改一个地方。同时,要求也会更严格,要求命名前缀规范一致。如果不规范一致也可以通过配置对象(用一个对象来保存每一个属性名)来解决,但看起来就更麻烦了。
只要在代码看得明白的情况下,尽量抽取公共部分,但也不要强求,过犹不及。