fix: 处理菜单权限相关判断与筛选问题
This commit is contained in:
@@ -1,33 +1,38 @@
|
||||
import { reactive, computed, toRefs } from 'vue';
|
||||
import type { PermissionCode } from '@/types';
|
||||
import { fetchPermissions } from '@/api/menu';
|
||||
import { fetchAuthData } from '@/api/menu';
|
||||
|
||||
interface PermissionState {
|
||||
/** 权限编码集合 */
|
||||
codes: Set<PermissionCode>;
|
||||
/** 角色列表 */
|
||||
roles: string[];
|
||||
/** 是否已加载 */
|
||||
loaded: boolean;
|
||||
}
|
||||
|
||||
const state = reactive<PermissionState>({
|
||||
codes: new Set(),
|
||||
roles: [],
|
||||
loaded: false,
|
||||
});
|
||||
|
||||
export function usePermissionStore() {
|
||||
/**
|
||||
* 从后端加载权限编码
|
||||
* 从后端加载权限编码和角色列表
|
||||
*/
|
||||
const loadPermissions = async () => {
|
||||
if (state.loaded) return;
|
||||
|
||||
try {
|
||||
const codes = await fetchPermissions();
|
||||
state.codes = new Set(codes);
|
||||
const { roleList, permsList } = await fetchAuthData();
|
||||
state.codes = new Set(permsList);
|
||||
state.roles = roleList;
|
||||
state.loaded = true;
|
||||
} catch (err) {
|
||||
console.error('加载权限失败:', err);
|
||||
state.codes = new Set();
|
||||
state.roles = [];
|
||||
state.loaded = true;
|
||||
}
|
||||
};
|
||||
@@ -37,12 +42,13 @@ export function usePermissionStore() {
|
||||
*/
|
||||
const clearPermissions = () => {
|
||||
state.codes = new Set();
|
||||
state.roles = [];
|
||||
state.loaded = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断是否拥有某个权限
|
||||
* @param code 权限编码,如 'user:delete'
|
||||
* @param code 权限编码,如 'events.list.view'
|
||||
*/
|
||||
const hasPermission = (code: PermissionCode): boolean => {
|
||||
return state.codes.has(code);
|
||||
@@ -55,6 +61,21 @@ export function usePermissionStore() {
|
||||
return codes.some((code) => state.codes.has(code));
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断是否拥有某个角色
|
||||
* @param role 角色标识,如 'admin'、'coo'
|
||||
*/
|
||||
const hasRole = (role: string): boolean => {
|
||||
return state.roles.includes(role);
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断是否拥有任意一个角色
|
||||
*/
|
||||
const hasAnyRole = (roles: string[]): boolean => {
|
||||
return roles.some((role) => state.roles.includes(role));
|
||||
};
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
loaded: computed(() => state.loaded),
|
||||
@@ -62,5 +83,7 @@ export function usePermissionStore() {
|
||||
clearPermissions,
|
||||
hasPermission,
|
||||
hasAnyPermission,
|
||||
hasRole,
|
||||
hasAnyRole,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user