[Vuejs]-Vue Router – redirect to the same route does not triggers afterEach() guard

0👍

This solution won’t work for all cases, but it could work for the example you mentioned if you implement an additional manual navigation guard in your router’s beforeEach hook.

Assume you have the following code where a user tries to navigate from /home to /login and ends up back on /home without the afterEach hook firing:

router.beforeEach((to, from, next) => {
  if (user.isAuthenticated() && to.path === '/login') {
    return next('/home')
  }
  return next()
})

router.afterEach(() => {
  // some logic
})

Refactor this to:

const afterEach = function() {
  // some logic
}

router.beforeEach((to, from, next) => {
  if (user.isAuthenticated() && to.path === '/login') {
    if (from.path === '/home') {
      afterEach()
    }
    return next('/home')
  }
  return next()
})

router.afterEach(afterEach)

Leave a comment