Bang Hu
1 天以前 8a709ba6db50831048f9c3e2452ea6dc6c3de36f
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
 * @Description: 
 * @Version: 2.0
 * @Autor: wuyun
 * @Date: 2023-01-30 15:39:36
 * @LastEditors: wuyun
 * @LastEditTime: 2023-10-07 14:10:56
 */
/**
 * v-auth
 * 按钮权限控制
 * 接收参数:string类型/Ref<string>类型/Reactive<string>类型
 * 
 * 'auth-view' 查看权限,页面 详情
 * 'auth-btn' 按钮权限,新增 修改
 * 页面书写形式 例:页面遮罩
 *  <WithoutPermissionModel v-auth="['device:deviceManagement:view','auth-view']"></WithoutPermissionModel>
 * 按钮权限
 *  v-auth="['device:deviceManagement:view','auth-btn']"
 */
 
import { usePermissionStoreHook } from '@/stores/modules/permission';
import { Directive } from 'vue';
import type { DirectiveBinding } from 'vue';
 
function typeOperate(hasPermission:boolean,el:HTMLElement,value: string[]) {
  let valStr=value.join()
  
  if (hasPermission) {
    if (valStr.indexOf('auth-view') > -1) {
      // 页面权限,是否显示页面遮罩,存在不显示
      el.style.display = 'none'
    } else if (valStr.indexOf('auth-btn') > -1) {
      // 按钮权限, 存在 显示
     el.style.display = 'flex'
    }
  } else {
     if (valStr.indexOf('auth-view')  > -1) {
      // 页面权限没有显示遮罩
      el.style.display = 'block'
    } else if (valStr.indexOf('auth-btn')  > -1) {
      // 按钮权限没有不显示
       el.style.display = 'none'
    }
  }
}
export const auth: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    // value 获取用户使用自定义指令绑定的内容
    const { value } = binding
    // 获取用户所有的权限按钮
    const permissionBtn = usePermissionStoreHook().buttonAuth
    // 判断用户使用自定义指令,是否使用正确了
    if (value && value instanceof Array && value.length > 0) {
      const permissionFunc = value
      //判断传递进来的按钮权限,用户是否拥有
      //Array.some(), 数组中有一个结果是true返回true,剩下的元素不会再检测
      const hasPermission = permissionBtn.some((role: any) => {
 
        return permissionFunc.includes(role.code)
      })
      nextTick(()=>{
        typeOperate(hasPermission,el,value)
      })
    } else {
      throw new Error('need roles! Like v-permission="[\'admin\',\'editor\']"')
    }
  }
};
export default auth;