最近在看同事代码时看到一段很长很长的代码,了解了一下大概功能就是在一个长列表里面有几十种类型的订单,一种或多种订单点击跳转对应的详情页,也就是说可能类型1跳转详情a,类型2和类型3跳转详情b,类型4,5,6跳转详情c… 反正就是多对一的关系。其实写起来也简单,直接if-else
就完事,当时同事是这样写的
handleClick(type) {
if(type === 1) {
// do sth
} else if(type ===2 || type === 3) {
// do sth
} else if(type === 5 || type === 6 || type === 10) {
}
// 下面还很多...
}
随着项目的迭代,有些7,8种类型共一个详情页的,写起来代码就变得挺长了,也不好读,其实可以使用include
进行优化,这样判断条件那里看起来就清爽一些,但是if-else
还是太长了, 其实可以使用设计模式中的策略模式进行优化,然后配合es6的 Map类型使可读性更高一些
data() {
return {
arr1: [2,3]
arr2: [5,6,7,8,9]
// more arr...
}
}
handleClick(type) {
let typeMap = new Map()
typeMap.set(1, () => {
// do sth
})
typeMap.set(this.arr1, () => {
// do sth
})
typeMap.set(this.arr2, () => {
// do sth
})
// more...
const key = arr1.includes(type) ? arr1 : arr2.includes(type) ? arr2 : type
typeMap.get(type)(key)
}
完事