auth.ts
1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 权限指令
* 使用方式:v-auth="'system:user:add'" 或 v-auth="['system:user:add', 'system:user:edit']"
*/
import type { Directive } from "vue";
import { useUserStore } from "@/stores";
export const auth: Directive = {
mounted(el, binding) {
const { value } = binding;
const userStore = useUserStore();
if (!value) return;
const authorities = Array.isArray(value) ? value : [ value ];
const hasPermission = userStore.hasAuthority(authorities);
if (!hasPermission) {
el.remove();
}
},
updated(el, binding) {
const { value } = binding;
const userStore = useUserStore();
if (!value) return;
const authorities = Array.isArray(value) ? value : [ value ];
const hasPermission = userStore.hasAuthority(authorities);
if (!hasPermission) {
// 如果元素已存在但无权限,移除它
if (el.parentNode) {
el.remove();
}
} else {
// 如果有权限但元素不存在,需要重新添加(这种情况较少见)
// 这里不做处理,因为通常元素已经在 mounted 时被移除了
}
},
};