vue 权限控制的思考

vue 权限控制的思考

我们的项目一般来说分为三个部分 - 路由控制 - 组件控制 - 接口控制

但是公司的后端是只处理了接口。针对接口进行控制。

在这样的前提下, 对权限控制进行一下梳理

路由控制

一般来说在 route 的 mate 里面添加权限。 然后 beforeEach
的时候对权限进行判断。没有对应的权限就跳到404页面

组件控制

在网络中搜索,一般都是用自定义指令进行处理。 但是这样有一个问题。
他需要挂载后然后移除子元素

我认为可以用 v-if 来省略这个问题

伪代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<template>
<template v-if="hasPermission">
<slot></slot>
</template>
</template>
<script lang="ts">
export default {
prop: {
permission: {
type: String,
}
},
data() {
return {
hasPermission: false,
}
},
created() {
const permissions = this.$store.state.permissions;
this.hasPermission = permissions.includes(this.permission);
}

}
</script>

接口控制

用装饰器实现

1
2
3
4
5
6
7
8
9
10
11
function apiRole(permission: string) {
const hasPermission = Permissions.includes(permission); // 这里做权限判断 return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
if (!hasPermission) {
descriptor.value = () => { } // 置为空函数 }
}
};class Api() {
@apiRole('LIST')
fetchData() {
console.log('123')
}
}

通过装饰器可以控制是否调用接口