Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue router next() function don't work in Promise in router.beforeEach

I have the following code:

router.beforeEach((to, from, next) => {
  if (to.name !== from.name) {
    store
      .dispatch("fetchCurrentUser")
      .then(() => {
        console.log('then');
        // do something
        next();
      })
      .catch(() => {
        console.log('catch');
        router.push("/login");
        next();
    });
  } else {
    next();
  }
  // next();
});

I'm trying to get the current user, and if this succeeds, then do something with this data, and if the request is not successful, then redirect the user to the login page. But next () calls do not work, I get the "then" or "catch" in the console, but the redirect does not occur and an infinite loop begins. But if I take next () from condition (commented row) the redirect works fine.

like image 359
Gosha null Avatar asked Mar 27 '19 14:03

Gosha null


People also ask

What does next () do in vue router?

next(false): abort the current navigation. If the browser URL was changed (either manually by the user or via back button), it will be reset to that of the from route.

What is router beforeEach?

beforeEach — called globally when a new navigation starts. beforeRouteUpdate — called on the route component when it's reused. beforeResolve — called globally when route component guards are done. afterEach — called globally when everything is resolved.

Can we define multiple router outlets in a component vue?

Instead of having one single outlet in your view, you can have multiple and give each of them a name. A router-view without a name will be given default as its name. A working demo of this example can be found here.


1 Answers

To redirect you should use next('/') or next({ path: '/' }).

From the documentation:

next: Function: this function must be called to resolve the hook. The action depends on the arguments provided to next:

next(): move on to the next hook in the pipeline. If no hooks are left, the navigation is confirmed.

next(false): abort the current navigation. If the browser URL was changed (either manually by the user or via back button), it will be reset to that of the from route.

next('/') or next({ path: '/' }): redirect to a different location. The current navigation will be aborted and a new one will be started. You can pass any location object to next, which allows you to specify options like replace: true, name: 'home' and any option used in router-link's to prop or router.push

like image 80
Jairo Avatar answered Sep 18 '22 13:09

Jairo