记一次项目中对if-else判断的优化, 本人技术比较菜, 不喜勿喷, 如有建议欢迎提出
在项目中有一个需求:
在表单中通过rentUnit下拉框、billingType下拉框、conversionType下拉框的值判断yearTypeShow、conversionTypeShow下拉框是否显示
if (rentUnit === 0 && billingType === 1) {
this.conversionTypeShow = 1
this.yearTypeShow = conversionType === 1 ? 1 : 0
} else if (rentUnit === 0 && billingType === 2) {
this.conversionTypeShow = 1
this.yearTypeShow = conversionType === 1 ? 1 : 0
} else if (rentUnit === 1 && billingType === 1) {
this.conversionTypeShow = 1
this.yearTypeShow = conversionType === 1 ? 1 : 0
} else if (rentUnit === 1 && billingType === 2) {
this.conversionTypeShow = 1
this.yearTypeShow = conversionType === 1 ? 1 : 0
} else if (rentUnit === 2) {
this.conversionTypeShow = 0
this.yearTypeShow = billingType === 2 ? 1 : 0
} else if (rentUnit === 3) {
this.conversionTypeShow = 0
this.yearTypeShow = billingType === 2 ? 1 : 0
} else if (rentUnit === 4 && billingType === 1) {
this.conversionTypeShow = 1
this.yearTypeShow = conversionType === 1 ? 1 : 0
} else if (rentUnit === 4 && billingType === 2) {
this.conversionTypeShow = 1
this.yearTypeShow = conversionType === 1 ? 1 : 0
} else if (rentUnit === 5) {
this.conversionTypeShow = 0
this.yearTypeShow = billingType === 2 ? 1 : 0
} else if (rentUnit === 6 && billingType === 1) {
this.conversionTypeShow = 0
this.yearTypeShow = 1
} else if (rentUnit === 6 && billingType === 2) {
this.conversionTypeShow = 1
this.yearTypeShow = conversionType ? conversionType === 1 ? 1 : 0 : 1
}优化后
var obj = {
0: () => {
this.conversionTypeShow = true
this.yearTypeShow = conversionType ? conversionType === 1 : true
},
1: () => {
this.conversionTypeShow = true
this.yearTypeShow = conversionType ? conversionType === 1 : true
},
2: () => {
this.conversionTypeShow = false
this.yearTypeShow = billingType === 2
},
3: () => {
this.conversionTypeShow = false
this.yearTypeShow = billingType === 2
},
4: () => {
this.conversionTypeShow = true
this.yearTypeShow = conversionType ? conversionType === 1 : true
},
5: () => {
this.conversionTypeShow = false
this.yearTypeShow = billingType === 2
},
6: () => {
this.conversionTypeShow = !billingType === 1
this.yearTypeShow = billingType === 1 ? true : conversionType ? conversionType === 1 : true
}
}
obj[rentUnit]()