最近在弄个人网站,开始更系统的思考一些优雅写法,之前工作中经常运用到的多状态操作
最开始是这样写,写好一个, 其他复制粘贴,虽然直接,但是代码块略微庞大,这种简单赋值尚且如此,更不用说其他复杂操作了
let room = this.$route.path.split('/').splice(-1).join()
let current = 0
if(room === 'porch'){
current=1
}else if(room === 'living') {
current=2
}else if(room === 'dining') {
current=3
}else if(room === 'study') {
current=4
}else if(room === 'happy') {
current=5
}else if(room === 'balcony') {
current=6
}else if(room === 'bedroom') {
current=7
}else if(room === 'washroom') {
current=8
}
后来对于这种简单的 我就改成switch了
let room = this.$route.path.split('/').splice(-1).join()
let current
switch(room){
case 'porch':
current=1
break
case 'living':
current=2
break
case 'dining':
current=3
break
case 'study':
current=4
break
case 'happy':
current=5
break
default:
current=0
break
}
但是依然觉得有点low呀,人生还是要不断尝试,果然还是有更好的方式,
let room = this.$route.path.split('/').splice(-1).join()
let item = {
'porch': [1], // 之所以用数组是为了方便加其他参数与操作
'living': [2],
'dining':[3],
'study': [4],
'happy': [5],
'balcony': [6],
'default':[0]
}
let current = 0
const roomEvent= (room) => {
let action = item [room] || item ['default']
current = action[0]
}
// 调用传参即可
roomEvent(room)
最后,还可以继续尝试……
比如Map,Map优点很多,在这里比较有用的是Map 的键可以是任何值
let room = this.$route.path.split('/').splice(-1).join()
let item = new Map({
['porch', [1]], // 之所以用数组是为了方便加其他参数与操作
['living', [2]],
['dining',[3]],
['study', [4]],
['happy', [5]],
['balcony', [6]],
['default',[0]]
})
let current = 0
const roomEvent= (room) => {
let action = item.get(room) || item.get('default')
current = action[0]
}
roomEvent(room)
对于我来说,到这种程度已经足够了,面对更为复杂的逻辑,我看大牛还可以用正则匹配,更适合那种比较规律的状态码,不过我这里不太适合。