ruoyi-plus-soybean/src/store/modules/route/index.ts

75 lines
2.2 KiB
TypeScript
Raw Normal View History

import { ref } from 'vue';
import type { Ref } from 'vue';
import type { Router } from 'vue-router';
import { defineStore } from 'pinia';
import { constantRoutes } from '@/router';
import { useBoolean } from '@/hooks';
import { fetchUserRoutes } from '@/service';
import { findAuthRouteByKey } from '@/utils';
/** 路由状态 */
interface RouteStore {
/** 动态路由 */
routes: Ref<AuthRoute.Route[]>;
/** 设置动态路由数据 */
setRoutes(data: AuthRoute.Route[]): void;
/** 是否添加过动态路由 */
isAddedDynamicRoute: Ref<boolean>;
/** 初始化动态路由 */
initDynamicRoute(router: Router): Promise<void>;
/**
*
* @description getRouteName getRoutePath 使 getRouteName
*/
getRouteName(key: AuthRoute.RouteKey): AuthRoute.RouteKey;
/**
*
* @description getRouteName getRoutePath 使 getRouteName
*/
2022-01-05 01:35:32 +08:00
getRoutePath(key: AuthRoute.RouteKey): AuthRoute.RoutePath | undefined;
/** 获取路由路径 */
getRouteTitle(key: AuthRoute.RouteKey): string | undefined;
}
export const useRouteStore = defineStore('route-store', () => {
const routes = ref<AuthRoute.Route[]>([]);
function setRoutes(data: AuthRoute.Route[]) {
routes.value = data;
}
const { bool: isAddedDynamicRoute, setTrue: setAddedDynamicRoute } = useBoolean();
async function initDynamicRoute(router: Router) {
const routes = await fetchUserRoutes();
routes.forEach(route => {
router.addRoute(route);
});
setAddedDynamicRoute();
}
function getRouteName(key: AuthRoute.RouteKey) {
return key;
}
function getRoutePath(key: AuthRoute.RouteKey) {
const allRoutes = [...constantRoutes, ...routes.value];
const item = findAuthRouteByKey(key, allRoutes);
return item?.path;
}
function getRouteTitle(key: AuthRoute.RouteKey) {
const allRoutes = [...constantRoutes, ...routes.value];
const item = findAuthRouteByKey(key, allRoutes);
return item?.meta?.title;
}
const routeStore: RouteStore = {
routes,
setRoutes,
isAddedDynamicRoute,
initDynamicRoute,
getRouteName,
getRoutePath,
getRouteTitle
};
return routeStore;
});