SoFunction
Updated on 2025-04-05

Detailed explanation of the solution to the vue beforeEach dead loop problem

What is beforeEach?

beforeEach is a vue-router route navigation hook, which I usually use as route guard.

What is a route guard?

Doing some verification before routing, such as login verification, is a common requirement in the website. In this regard, the beforeRouteUpdate provided by vue-route can conveniently implement navigation-guards. The name navigation-guards sounds weird, but since the official document is translated like this, let's call it that way. **

Document address:/zh/guide/advanced/

For example, when we are not logged in, jump to the login page. If logged in, it will jump normally.

Let's take a look at the dead loop code below.

export const router = new Router(RouterConfig);
((to, from, next) => {
  let token = ('token');
  if (token) {
    next();
  } else {
    next({path: '/p404'})
  }
});

When the token does not exist in the session, it jumps to /p404. At this time, the route changes and makes a judgment again, it jumps to /404 again, which creates a dead loop. Make a judgment in the code. If you jump to p404, let it go to the route with peace of mind. The modified code is as follows.

export const router = new Router(RouterConfig);
((to, from, next) => {
  let token = ('token');
  if (token) {
    next();
  } else {
    if ( == '/p404') {
      next();
    } else {
      next({path: '/p404'})
    }
  }
});

This is the end of this article about the detailed explanation of the solution to the vue beforeEach dead loop problem. For more related vue beforeEach dead loop content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!