Javascript vue路由器重定向在路由推送上不起作用
我已配置以下路由器:Javascript vue路由器重定向在路由推送上不起作用,javascript,vue.js,vuejs2,vue-router,Javascript,Vue.js,Vuejs2,Vue Router,我已配置以下路由器: const router = new Router({ mode: 'history', routes: [ // root { path: '/', component: ComponentPage, redirect: routePrefix.public, children: [ // public { path: routePrefix.p
const router = new Router({
mode: 'history',
routes: [
// root
{
path: '/',
component: ComponentPage,
redirect: routePrefix.public,
children: [
// public
{
path: routePrefix.public,
component: ComponentPage,
redirect: `${routePrefix.public}/login`,
children: [
{
path: `${routePrefix.public}/login`, component: LoginPage,
}],
},
// private
{
path: routePrefix.private,
component: ComponentPage,
children: [
{
path: `${routePrefix.private}/u`, component: PrivatePage,
}],
}],
}],
});
正如你所看到的,有两个主要部分;一个公共的,一个私人的。
此外,我还为授权配置了以下导航保护:
router.beforeEach((to, from, next) => {
console.log(`registered request to redirect from
'${from.fullPath}' to '${to.fullPath}'`);
if (to.fullPath.startsWith(routePrefix.private) &&
!Store.getters['auth/isAuthenticated']) {
console.log('-> reroute to public main');
next(routePrefix.public);
} else if (to.fullPath.startsWith(routePrefix.public) &&
Store.getters['auth/isAuthenticated']) {
console.log('-> reroute to private main');
next(routePrefix.private);
} else {
next();
}
});
如果您想知道路由前缀是什么样子的,请看:
const routePrefix = {
public: '/p', private: '/x',
};
没什么特别的
问题
我打开页面localhost:8080/
,按预期将/
重定向到/p/login
。成功登录后,我执行了一个Router.push('/')
,目的是再次重新路由用户
这个想法是,/
应该再次重定向到/p/login
,导航卫士在这里启动并将其重定向到/x/
。。。但事实并非如此。它保持在/
上
难道它不应该将其重定向到主页之外吗?我怎样才能解决这个问题?我没有找到解决这个问题的办法。我已经达到了我的目标,直接推动到理想的目的地,而不是让重新路由发挥它的魔力。这是有效的。为什么在登录后推送('/'),而不是直接到
/x
?@btl主要是因为身份验证模块不知道路由,我认为这是一个很好的解决方案,因为它不需要任何额外的代码,因为您正在注册一个全局防护,需要检查的只是在if(…){…}if else(){}else{}
之前添加if(Store.getters['auth/isAuthenticated']{next()}…
。如果我路由到/
,那么else
案例将在导航保护中触发,这是一个next()
调用。为什么您的解决方案会有任何不同的工作方式?所有这些重定向不会让人感到困惑吗?不管怎么说,警卫并不是只用于重定向他们的目标,我想这就是这里的问题所在。你真的应该直接进入你想去的路线,并对该路线应用防护,这些类型的全局防护解决方案很少能很好地工作。