【问题标题】:vue-router - Navigation cancelled from "/" to "/password" with a new navigationvue-router - 使用新导航取消从“/”到“/password”的导航
【发布时间】:2021-03-24 20:19:18
【问题描述】:

试图导航到密码页面,vue-router 抛出此错误

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

导航到密码页面已成功重定向,但不确定为什么会抛出此错误。我之前没有观察到这个错误。

Vue 路由器版本: vue-router@3.3.4

点击一个按钮做this.$router.push({name: 'password', query: {username: this.username}})

在路由器/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')
  }
]

}

【问题讨论】:

标签: javascript vue.js vue-router


【解决方案1】:

我最近遇到了同样的错误。发生这种情况是因为 vue 路由器无法重定向两次(这意味着您无法在重定向的路由中重定向)。 documentation中提到了这一点

确保在通过导航守卫的任何给定传递中,下一个函数只被调用一次。它可以出现多次,但前提是逻辑路径没有重叠,否则钩子永远不会被解析或产生错误。

我有一个解决方法是创建一个隐藏的vue-route 组件,其中包含您要重定向到的路由,然后单击。

示例:

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

当您想要重定向时(可能是在用户输入密码后),您可以在此链接上触发点击事件

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

【讨论】:

    【解决方案2】:

    您应该添加catch() 来捕获此类错误:

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

    更多信息请访问VueRouter documentation

    【讨论】:

      【解决方案3】:

      Vue Router 还提供了一个名为isNavigationFailure 的方法来识别错误:

      import VueRouter from 'vue-router'
      const { isNavigationFailure, NavigationFailureType } = VueRouter
      
      // 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')
        }
      })
      

      更多信息here

      【讨论】:

        猜你喜欢
        • 2022-06-15
        • 2018-09-12
        • 2019-09-22
        • 1970-01-01
        • 2019-04-17
        • 1970-01-01
        • 2021-04-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多