场景
系统基于 若依 二次开发;动态的加载路由已经集成好了;
根据业务需要,不同角色访问的首页是不同的,一顿操作后,每次访问 / 时一直会进入404页面内。
原本的代码
permission.js
router.beforeEach((to, from, next) => {
if (getToken()) {
/* has token*/
if (to.path === "/login") {
next({ path: "/" });
} else {
if (store.getters.roles.length === 0) {
isRelogin.show = true;
// 判断当前用户是否已拉取完user_info信息
store
.dispatch("GetInfo")
.then((res) => {
isRelogin.show = false;
store.dispatch("GenerateRoutes").then(accessRoutes => {
router.addRoutes(accessRoutes); // 动态添加可访问路由表
next({ ...to, replace: true });
});
})
.catch(err => {
store.dispatch("LogOut").then(() => {
next({ path: "/" });
});
});
} else {
next();
}
}
} else {
// 没有token
if (whiteList.indexOf(to.path) !== -1) {
next();
} else {
next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
}
}
});
router.js
// 公共路由
export const constantRoutes = [
{
path: "/redirect",
component: Layout,
hidden: true,
children: [
{
path: "/redirect/:path(.*)",
component: () => import("@/views/redirect"),
},
],
},
{
path: "/login",
component: () => import("@/views/login"),
hidden: true,
},
{
path: "/404",
component: () => import("@/views/error/404"),
hidden: true,
},
{
path: "/401",
component: () => import("@/views/error/401"),
hidden: true,
}
];
export default new Router({
mode: "history",
scrollBehavior: () => ({ y: 0 }),
routes: [...constantRoutes],
});
accessRoutes: accessRoutes是经过store中处理之后的,最终结构如下
[
{
path: "/xx/xx",
component: Layout,
children: [{}, ...],
},
...多个路由,
{
path: "*",
redirect: '/404',
hidden: true
}
];
因为业务需要,不同的角色访问地址 / 时,跳转的页面不同。以及一些其他原因。所以需要对accessRoutes进行处理;
修改之后的代码
permission.js
store.dispatch("GenerateRoutes").then(accessRoutes => {
const mainRoute = {
path: "/",
component: () => import("@/layout/main.vue"),
redirect: getFirstPath("", accessRoutes),
children: [...accessRoutes],
};
router.addRoutes([mainRoute]);
next({ ...to, replace: true });
});
但是最终运行结果是,地址栏访问动态的路由 /xx/xx 时可以访问到;但是访问 / 时却一直会跳转到404页面中;
原因
网上查博客,查到一种方法可行,恰巧也是使用的若依;
该方法是在 router.addRoutes 之后对角色进行判断,然后跳转不同的相应的页面。
🙄But,问题解决了,但是我根据角色对"/"路由设置不同的 redirect 为什么会一直404呢?
网上查不到,只能自己调试代码了。。。
1. 404原因?
先在router.addRoute之后的next行调试,这个时候动态路由已经添加进去了。
此时,to.path == "/"。一直向下到VueRouter中match匹配路由的地方,在pathList中发现通配符 * 的路由在 "" 之前。
path: "/" 或 path: "" 的路由,vueRouter会在内部转换成 ""
所以,每次访问 "/"的时候,会一直提示404;
2. 通配符 * 在 "" 之前?
对router.addRoute进行调试,一直向下找到addRouteRecord方法,你会发现,vueRouter添加router record的时候,对新进来的routes数组是以深度优先进行遍历的。
而代码中的 addRoute 添加的路由结构是:
[
{
path: "/",
redirect: "xxx",
children: [..., ..., { path: "*", redirect: "/404" }]
}
]
所以,pathList中的的 "*" 会在 "" 之前,就会导致每次访问“/”的时候一直跳转到404页面;
问题原因找到了,所以只需要对通配符的路由提出来,放到最后就可以完美解决问题了!
🤣
router.addRoutes([mainRoute, { path: '*', redirect: '/404', hidden: true }]);