frank Walleway
frank Walleway

Reputation: 136

Vue-router beforeEach stuck in infinite loop when using next()

I'm having this problem where i cant use next('/login'). This is my code:

*/ all imports that are needed 

Vue.use(Router);

const routes = [
{path: '/', component: Home},
{path: '/admin', component: Admin},
{path: '/login', component: Login}]

var route = new Router({
routes: routes,
mode: 'history' });

route.beforeEach((to, from , next) => {
console.log(to.fullPath)
next('/login');
});

new Vue({
  el: '#app',
  router: route,
  template: '<App/>',
  components: {
    App
  }
})

It works when i only use next() but when i give the next() function a route it's stuck within an infinite loop

console screenshot

Upvotes: 7

Views: 14877

Answers (1)

Crackers
Crackers

Reputation: 1125

You have to prevent to call next('/login') if you are already directing to '/login'.

For example:

route.beforeEach((to, from , next) => {
  console.log(to.fullPath)
  if (to.path !== '/login') {
    next('/login');
  } else {
    next();
  }
});

Upvotes: 23

Related Questions