77 lines
2.1 KiB
TypeScript
77 lines
2.1 KiB
TypeScript
import { RouteRecordRaw } from 'vue-router';
|
||
import { defineStore } from 'pinia';
|
||
import { constantRoutes } from '@/router';
|
||
import { store } from '@/store';
|
||
import { listRoutes } from '@/api/menu';
|
||
import { ref } from 'vue';
|
||
|
||
const modules = import.meta.glob('../../views/**/**.vue');
|
||
export const Layout = () => import('@/layout/index.vue');
|
||
|
||
const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
|
||
const res: RouteRecordRaw[] = [];
|
||
routes.forEach(route => {
|
||
const tmp = { ...route } as any;
|
||
// ✅ 保存原始名称到 meta,用于菜单显示
|
||
tmp.meta = {
|
||
...tmp.meta,
|
||
title: tmp.name || tmp.menuName // 原始名称用于显示
|
||
};
|
||
// ✅ name 使用路径生成唯一值
|
||
tmp.name = tmp.path || tmp.opturl;
|
||
|
||
// if (hasPermission(roles, tmp)) {
|
||
tmp.path = tmp.opturl;
|
||
if (tmp.type == '0') {
|
||
tmp.component = Layout;
|
||
} else {
|
||
const component = modules[`../../views${tmp.opturl}.vue`] as any;
|
||
if (component) {
|
||
tmp.component = component;
|
||
} else {
|
||
tmp.component = modules[`../../views/error-page/404.vue`];
|
||
}
|
||
}
|
||
res.push(tmp);
|
||
if (tmp.children) {
|
||
tmp.children = filterAsyncRoutes(tmp.children, roles);
|
||
}
|
||
// }
|
||
});
|
||
return res;
|
||
};
|
||
|
||
// setup
|
||
export const usePermissionStore = defineStore('permission', () => {
|
||
// state
|
||
const routes = ref<RouteRecordRaw[]>([]);
|
||
const addRoutes = ref<RouteRecordRaw[]>([]);
|
||
|
||
// actions
|
||
function setRoutes(newRoutes: RouteRecordRaw[]) {
|
||
addRoutes.value = newRoutes;
|
||
routes.value = constantRoutes.concat(newRoutes);
|
||
}
|
||
|
||
function generateRoutes(roles: string[]) {
|
||
return new Promise<RouteRecordRaw[]>((resolve, reject) => {
|
||
listRoutes()
|
||
.then(response => {
|
||
const asyncRoutes: any = response;
|
||
const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
|
||
setRoutes(accessedRoutes);
|
||
resolve(accessedRoutes);
|
||
})
|
||
.catch(error => {
|
||
reject(error);
|
||
});
|
||
});
|
||
}
|
||
return { routes, setRoutes, generateRoutes };
|
||
});
|
||
|
||
// 非setup
|
||
export function usePermissionStoreHook() {
|
||
return usePermissionStore(store);
|
||
}
|