7

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

1 Answer 1

23

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();
  }
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! That fixed it
This still breaks in some cases. When testing this, if a user clicks to navigate to another protected route, the infinite loop starts again. Using afterEach like app.router.afterEach((to, from) => { with app.router.push('/login) does not have that issue.
@learnsomemore - could you elaborate? Do you mean I should be testing to.path != '/login' inside after each and redirect using app.router.push('login') instead of next?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.