51 lines
1.6 KiB
TypeScript
51 lines
1.6 KiB
TypeScript
import { permissionApi } from '@/api/admin'
|
|
import { ref, computed } from 'vue'
|
|
|
|
const userPermissions = ref<string[]>([])
|
|
const loadingPermissions = ref(false)
|
|
|
|
export const usePermission = () => {
|
|
const hasPermission = (permissionCode: string) => {
|
|
return userPermissions.value.includes(permissionCode)
|
|
}
|
|
|
|
const hasAnyPermission = (permissionCodes: string[]) => {
|
|
return permissionCodes.some(code => userPermissions.value.includes(code))
|
|
}
|
|
|
|
const hasAllPermissions = (permissionCodes: string[]) => {
|
|
return permissionCodes.every(code => userPermissions.value.includes(code))
|
|
}
|
|
|
|
const loadUserPermissions = async () => {
|
|
loadingPermissions.value = true
|
|
try {
|
|
const permissions = await permissionApi.getUserPermissions()
|
|
userPermissions.value = permissions && Array.isArray(permissions) ? permissions.map(p => p.permissionCode) : []
|
|
// 存储权限到本地存储,供路由守卫使用
|
|
localStorage.setItem('userPermissions', JSON.stringify(userPermissions.value))
|
|
} catch (error) {
|
|
console.error('加载用户权限失败:', error)
|
|
userPermissions.value = []
|
|
localStorage.setItem('userPermissions', JSON.stringify([]))
|
|
} finally {
|
|
loadingPermissions.value = false
|
|
}
|
|
}
|
|
|
|
const clearPermissions = () => {
|
|
userPermissions.value = []
|
|
localStorage.removeItem('userPermissions')
|
|
}
|
|
|
|
return {
|
|
userPermissions: computed(() => userPermissions.value),
|
|
loadingPermissions: computed(() => loadingPermissions.value),
|
|
hasPermission,
|
|
hasAnyPermission,
|
|
hasAllPermissions,
|
|
loadUserPermissions,
|
|
clearPermissions
|
|
}
|
|
}
|