简体   繁体   中英

vue-router redirect not working on route push

I have the following router configured:

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,
            }],
        }],
    }],
});

now as you can see, there are two main parts; a public, and a private one. Additionally I have the following navigation guard configured for authorization:

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();
  }
});

If you're wondering what the route prefix look like, here you go:

const routePrefix = {
  public: '/p', private: '/x',
};

Nothing so special.

The problem

I open the page localhost:8080/ which redirects / to /p/login as expected. After a successful login, I perform a Router.push('/') with the intention to further re-route the user once again.

The idea is that / should get redirect to /p/login again, where the navigation guard kicks in and redirects it to /x/ ... But it doesn't. It stays on / .

Isn't it supposed to redirect it away from the main page? How can I fix it?

I didn't find a solution to this problem. I've reached my goal by pushing to the desired destination directly instead of letting the rerouting do its magic. This works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM