vue-router - Navigation cancelled from "/" to "/password" with a new navigation

Viewed 16007

Trying to navigate to password page, vue-router throwing this error

Uncaught (in promise) Error: Navigation cancelled from "/" to "/password" with a new navigation.

Navigating to password page is successfully redirected but not sure why this error is throwing. I didnt observe this error before.

Vue router version: vue-router@3.3.4

On click on a button doing this.$router.push({name: 'password', query: {username: this.username}})

In router/index.js

{
path: '/',
component: loginComponent,
children: [
  {
    path: '/',
    alias: '/login',
    name: 'login',
    component: () => import('../views/email.vue')
  },
  {
    path: 'password',
    name: 'password',
    component: () => import('../views/password.vue')
  }
]

}

3 Answers

I recently got the same error. this is happening because vue router can't redirect twice (that means you can't redirect in a redirected route). this is mentioned in the documentation

Make sure that the next function is called exactly once in any given pass through the navigation guard. It can appear more than once, but only if the logical paths have no overlap, otherwise the hook will never be resolved or produce errors.

I have a workaround for it which is to create a hidden vue-route component with the route you want to redirect to and then click.

example:

<router-link ref="redirect" :to="$route.query.redirect ? $route.query.redirect : '/'"></router-link>

and when you want to redirect (maybe in your case after the user enters the password) you can just trigger a click event on this link

this.$refs.redirect.$el.click()

You should add a catch() to catch such errors:

this.$router.push({
  name: 'password', 
  query: {
    username: this.username
  }
}).catch();

More information is available in the VueRouter documentation.

Vue Router also provides a method called isNavigationFailure to identify the error:

import { isNavigationFailure, NavigationFailureType } from 'vue-router'

// trying to access the admin page
router.push('/admin').catch(failure => {
  if (isNavigationFailure(failure, NavigationFailureType.redirected)) {
    // show a small notification to the user
    showToast('Login in order to access the admin panel')
  }
})

More info here.

Related