动态路由加载代码
正确的路由配置
{
path: "/Recruitment",
name: "Recruitment",
component: () => import("@/pages/recruitment/index.vue"),
redirect: "/Recruitment/recruitment-plan",
children: [
{
path: "recruitment-plan",
component: () =>
import("@/pages/recruitment/recruitment-plan/index.vue"),
},
],
},
注: 因为vue-route导航守卫中是通过 ‘to.name != null ‘ , 进行判断, 所以name值不可以缺少, 缺少会导致 进入下一个判断. 不断进行addRoute
async GenerateRoutes({ commit }: any, asyncRouter: RouteRecordRaw[] = []) {
const result = asyncRouter.map((item) => {
const temp = {
path: `/{item.path}`,
name: item.path,
component: () => import(`../pages/{item.component}`),
meta: {},
} as any;
if (item.children && item.children.length) {
temp["redirect"] = `/{item.path}/{item.children[0].path}`;
temp["children"] = item.children.map((k) => {
return {
path: k.path,
name: k.path, // 因为导航守卫是通过name值进行判断的, 所以不能缺少
component: () => import(`../pages/${k.component}`),
meta: {},
};
});
} else {
item.children = [];
}
return temp;
});
result.forEach(async (item) => {
await router.addRoute(item);
});
// 最后添加, 以免出现空白页问题
await router.addRoute({
path: "/:pathMatch(.*)*",
component: await loadComponent(`/src/pages/error/404/index.vue`),
meta: {
name: "404",
},
});
// 可以看是否怎么加载动态路由
console.log("routes:", router.getRoutes());
return result;
},
router.beforeEach代码
router.beforeEach((to: any, from: any, next: any) => {
NProgress.start();
const isLogin = getCookies(getTokenName());
if (isLogin) {
if (to.path === "/login") {
next();
}
//============== 重点
if (to.name != null) { // 这个判断条件因人而异, 动态路由很有必要不是出现白屏问题
next();
} else {
const lst = Session.get("userInfo")?.menuTreeList;
store.dispatch("GenerateRoutes", lst).then(() => {
next({ ...to, replace: true });
});
}
//=====================
} else {
if (to.path !== "/login") {
next({ path: "/login", query: { redirect: to.fullPath } });
} else {
next();
}
}
});