Navigation Guards beforeEach 无限循环

Navigation Guards beforeEach infinite loop

正在尝试使用导航守卫,但 next('/auth/login') 出现无限循环:

router.beforeEach((to, from, next) => {
  auth.validate().then((valid) => {
    if (!valid) {
      next('/auth/login')
    } else {
      next()
    }
  })
})

路由器已定义:

const router = new Router({
  routes: [
    {
      name: 'login',
      path: '/auth/login',
      component: login
    }
})

在我看来,当您的身份验证无效时,您的路由器会将您发送到 /auth/login 并在该页面上再次发送您。我在我的应用程序中以不同的方式处理这个问题,但是使用您的代码,您可以添加一种方法来检查页面的来源,使用路由中的 from 对象。

您需要一些东西来检查当前路线是否 /auth/login 然后忽略不重定向。

示例:

 if (!valid && from.path !== '/auth/login') {}

这不会重定向回 /auth/login,因为您来自该页面。