Kaynağa Gözat

增加空判断保护

shizhong 1 yıl önce
ebeveyn
işleme
75d0bdcc49

+ 22 - 1
src/directives/permission/hasPermi.ts

@@ -8,7 +8,7 @@ export function hasPermi(app: App<Element>) {
     const { wsCache } = useCache()
     const { value } = binding
     const all_permission = '*:*:*'
-    const permissions = wsCache.get(CACHE_KEY.USER).permissions
+    const permissions = wsCache.get(CACHE_KEY.USER)?.permissions ? wsCache.get(CACHE_KEY.USER)?.permissions : []
 
     if (value && value instanceof Array && value.length > 0) {
       const permissionFlag = value
@@ -25,3 +25,24 @@ export function hasPermi(app: App<Element>) {
     }
   })
 }
+
+export function hasPermiEvery(app: App<Element>) {
+  app.directive('hasPermiEvery', (el, binding) => {
+    const { wsCache } = useCache()
+    const { value } = binding
+    const all_permission = '*:*:*'
+    const permissions = wsCache.get(CACHE_KEY.USER)?.permissions ? wsCache.get(CACHE_KEY.USER)?.permissions : []
+    if (value && value instanceof Array && value.length > 0) {
+      const permissionFlag = value
+      const hasPermissions = permissionFlag.every((permission: string) => {
+        return all_permission === permission || permissions.includes(permission)
+      })
+
+      if (!hasPermissions) {
+        el.parentNode && el.parentNode.removeChild(el)
+      }
+    } else {
+      throw new Error(t('permission.hasPermission'))
+    }
+  })
+}

+ 1 - 1
src/directives/permission/hasRole.ts

@@ -8,7 +8,7 @@ export function hasRole(app: App<Element>) {
     const { wsCache } = useCache()
     const { value } = binding
     const super_admin = 'admin'
-    const roles = wsCache.get(CACHE_KEY.USER).roles
+    const roles = wsCache.get(CACHE_KEY.USER)?.roles ? wsCache.get(CACHE_KEY.USER)?.roles : []
 
     if (value && value instanceof Array && value.length > 0) {
       const roleFlag = value

+ 2 - 2
src/utils/permission.ts

@@ -12,7 +12,7 @@ export function checkPermi(value: string[]) {
     const { wsCache } = useCache()
     const permissionDatas = value
     const all_permission = '*:*:*'
-    const permissions = wsCache.get(CACHE_KEY.USER).permissions
+    const permissions = wsCache.get(CACHE_KEY.USER)?.permissions ? wsCache.get(CACHE_KEY.USER)?.permissions : []
     const hasPermission = permissions.some((permission) => {
       return all_permission === permission || permissionDatas.includes(permission)
     })
@@ -33,7 +33,7 @@ export function checkRole(value: string[]) {
     const { wsCache } = useCache()
     const permissionRoles = value
     const super_admin = 'admin'
-    const roles = wsCache.get(CACHE_KEY.USER).roles
+    const roles = wsCache.get(CACHE_KEY.USER)?.roles ? wsCache.get(CACHE_KEY.USER)?.roles : []
     const hasRole = roles.some((role) => {
       return super_admin === role || permissionRoles.includes(role)
     })