记录一次vue-router异步加载路由踩的坑。
1.加载路由配置代码
const WHITE_NAME_LIST: string[] = [];
export const getRouteNames = (array: any[]) =>
array.forEach((item) => {
WHITE_NAME_LIST.push(item.name);
getRouteNames(item.children || []);
});
getRouteNames(basicRoutes);
export function resetRouter() {
const { router } = appOptions;
router.getRoutes().forEach((route) => {
const { name } = route;
if (name && !WHITE_NAME_LIST.includes(name as string)) {
if (router.hasRoute(name)) router.removeRoute(name);
}
});
}
export function loadRoutes(rConfig?: Array<menuDItem>) {
resetRouter();
const accountStore = useAccountStore();
const { router } = appOptions;
let routesConfig: Array<menuDItem> = [];
if (rConfig) accountStore.setRoutesConfig(rConfig);
routesConfig = rConfig ?? accountStore.getRouesConfig;
if (routesConfig && routesConfig.length > 0) {
let routes = parseRoutes(routesConfig, asyncRoutes);
routes = formatRoutes(routes);
routes.forEach((route) => {
router.addRoute('layout', route);
});
router.options.routes[0].children = routes;
}
router.addRoute({
path: '/:pathMatch(.*)',
name: '*',
meta: { hidden: true },
redirect: '/404',
});
const rootRoute = router.options.routes.find((item) => item.path === '/');
const menuRoutes = rootRoute && rootRoute.children;
if (menuRoutes) {
setting().setMenuData(menuRoutes);
}
}
2.main.ts代码
import { router } from '@/router/index';
import { loadRoutes, setAppOptions } from '@/utils/routerUtil';
app.use(router);
setAppOptions({ router });
loadRoutes();
3.router.beforeEach重新加载页面代码
router.beforeEach((to, from, next) => {
if (to.matched.length === 0) {
next({
...to,
replace: true
});
} else {
next();
}
});