场景
系统基于 若依 二次开发;动态的加载路由已经集成好了;
根据业务需要,不同角色访问的首页是不同的,一顿操作后,每次访问 / 时一直会进入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 之后对角色进行判断,然后跳转不同的相应的页面。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。