日常开发的类型判断是再常见不过的场景,比如我们有如下场景:
管理员的角色id为1,普通员工的角色id为2,超级管理员的角色id为3,每个角色对应显示页面上不同的按钮。普通员工只能查看列表,不能新增和编辑和删除,管理员和超级管理员都可以进行新增和编辑。只有超级管理员才能进行删除。于是我们有以下代码:
<template>
<div>
<el-button v-if="roleId !== 2" @click="handleClick">新增</el-button>
<el-button v-if="roleId !== 2" @click="handleClick">编辑</el-button>
<el-button v-if="roleId === 3" @click="handleClick">删除</el-button>
</div>
</template>
<script>
export default {
data() {
return {
roleId: null
}
},
created() {
this.roleId = localStorage.getItem('roleId')
if (this.roleId === 2) {
this.getNormalList()
}
if (this.roleId === 3) {
this.getSuperManageList()
}
if (this.roleId === 1) {
this.getManageList()
}
},
methods: {
handleClick() {
// 普通员工
if (this.roleId === 2) {
return
}
},
getManageList() {
},
getNormalList() {
},
getSuperManageList() {
}
}
}
</script>
/可以看到,这一小部分示例代码里有很多写死的1、2、3。刚刚写好的时候不会有任何问题,但是随着我们页面越来越多,甚至项目中全局引入的时候,写死的数字满天飞。
终于有一天,事情发生了变化…
由于需求变更,后端角色字段需要调整。普通员工的字段要从2调整为4。心里暗暗的吐槽一番之后,我们傻眼了。
roleId满天飞,到处都是1、2、3。一处处找数字,一处处改。痛苦不易。
我们其实可以使用配置表的方式来优化一下:
<template>
<div>
<el-button v-if="roleId !== rolesConfig.normalRole" @click="handleClick">新增</el-button>
<el-button v-if="roleId !== rolesConfig.normalRole" @click="handleClick">编辑</el-button>
<el-button v-if="roleId === rolesConfig.superManagerRole" @click="handleClick">删除</el-button>
</div>
</template>
<script>
const rolesConfig = {
// 注:若后端代码有变化,则只需要修改这里的代码即可。
normalRole: 2,
managerRole: 1,
superManagerRole: 3
}
export default {
data() {
return {
roleId: null,
rolesConfig
}
},
created() {
this.roleId = localStorage.getItem('roleId')
if (this.roleId === rolesConfig.normalRole) {
this.getNormalList()
}
if (this.roleId === rolesConfig.superManagerRole) {
this.getSuperManageList()
}
if (this.roleId === rolesConfig.managerRole) {
this.getManageList()
}
},
methods: {
handleClick() {
// 普通员工
if (this.roleId === rolesConfig.normalRole) {
return
}
},
getManageList() {
},
getNormalList() {
},
getSuperManageList() {
}
}
}
</script>