Skip to content

权限 Hooks:useAuth ​

useAuth 是组件库的公共权限编程式判定 hooks(已从 BizAuthButton 内部提升至 packages/hooks),与 BizAuthButton、v-auth 指令共用同一全局权限集合,覆盖 tab 显隐、区块控制、路由守卫等非按钮场景。

注入权限集合 ​

应用启动或登录态切换时注入一次:

vue
<script setup lang="ts">
import { configureBizAuth } from 'vue3-ep-biz-lib'
import { getUserPermissions } from '@/api/auth'

// 方式一:码表数组
configureBizAuth(['order:view', 'order:export', 'user:manage'])

// 方式二:断言函数(对接后端任意权限模型)
configureBizAuth((code) => getUserPermissions().includes(code))

// 传 undefined 表示不启用权限控制(默认放行,fail-open)
</script>

编程式判定 ​

vue
<script setup lang="ts">
import { computed } from 'vue'
import { useAuth } from 'vue3-ep-biz-lib'

const { permissions, hasAuth } = useAuth()

// 响应式:configureBizAuth 变更后自动重渲染
const canExport = computed(() => hasAuth('order:export'))

// 数组为「任一命中即放行」
const canEdit = computed(() => hasAuth(['order:edit', 'order:admin']))
</script>

<template>
  <ElTabPane v-if="hasAuth('user:manage')" label="用户管理" />
  <div v-if="canExport">导出区块</div>
</template>

路由守卫 ​

ts
import router from './router'
import { configureBizAuth, checkBizAuth } from 'vue3-ep-biz-lib'

router.beforeEach((to) => {
  if (to.meta.auth && !checkBizAuth(to.meta.auth as string[])) {
    return { path: '/403' }
  }
})

API ​

useAuth(): { permissions, hasAuth } ​

成员类型说明
permissionsRef<BizAuthPermissions | undefined>全局权限集合(响应式,configureBizAuth 变更后自动同步)
hasAuth(codes?: string | string[]) => boolean权限判定:任一命中即放行;未配置集合时默认放行(fail-open)

相关独立函数 ​

函数说明
configureBizAuth(permissions?)注入权限集合(数组或断言函数);undefined 关闭控制
getBizAuthPermissions()读取全局权限集合 Ref
checkBizAuth(codes, permissions?)纯函数判定(可传局部集合覆盖全局,路由守卫等非 setup 场景使用)

与组件形态的关系 ​

形态适用场景
BizAuthButton按钮级(code + mode 隐藏 / 置灰)
v-auth 指令任意元素级(v-auth="'user:add'" / v-auth.disable)
useAuth()编程式(tab / 区块 / computed 联动)
checkBizAuth()非 setup 场景(路由守卫 / 工具函数)