在vue后台管理系统这块,经常通过使用路由全局守卫beforeEach和addroute来实现动态挂载路由。这一块总的思路虽然很好理解,但是其中有很多细节需要注意。
问题一:addRoute只需使用一次
控制addRoute:声明一个布尔值registerRouteFresh ,初始值为TRUE,当registerRouteFresh 为TRUE时,路由进行挂载,挂载完毕之后,变为FALSE
let registerRouteFresh = true;
router.beforeEach(async (to, from, next) => {
const account = window.localStorage.getItem('account');
// 已经登录
if (account) {
// 第一次挂载路由
if (registerRouteFresh) {
if (account === 'admax') {
routeadmin.forEach((i) => {
router.addRoute(i);
});
window.localStorage.setItem('menu', JSON.stringify(routeadmin));
}
next({ ...to, replace: true });
registerRouteFresh = false;
} else {
next();
}
// 没有登录,返回登录页面
} else {
}
});
问题二:next(路径)会造成无限循环
每一次导航路由的跳转,都会经过一遍路由全局守卫,如果直接去使用next(路径),就会不断进行路由判断,进入无限循环
比如:next(‘login’)返回登录页面
错误用法:
let registerRouteFresh = true;
router.beforeEach(async (to, from, next) => {
const account = window.localStorage.getItem('account');
// 已经登录
if (account) {
// 第一次挂载路由
if (registerRouteFresh) {
if (account === 'admax') {
routeadmin.forEach((i) => {
router.addRoute(i);
});
window.localStorage.setItem('menu', JSON.stringify(routeadmin));
}
//确保路由addroute执行完毕
next({ ...to, replace: true });
registerRouteFresh = false;
} else {
next();
}
// 没有登录,返回登录页面
} else {
next('login');
}
});
正确用法:
let registerRouteFresh = true;
router.beforeEach(async (to, from, next) => {
const account = window.localStorage.getItem('account');
// 已经登录
if (account) {
// 第一次挂载路由
if (registerRouteFresh) {
if (account === 'admax') {
routeadmin.forEach((i) => {
router.addRoute(i);
});
window.localStorage.setItem('menu', JSON.stringify(routeadmin));
}
next({ ...to, replace: true });
registerRouteFresh = false;
} else {
next();
}
// 没有登录,返回登录页面
} else {
if (to.path === '/login') {
next();
} else {
next('login');
//next('login'):执行这一步时,进行路由守卫判断,正好to.path === '/login',从守卫中出来
}
}
});