如果登录并想要访问登录/注册页面,我想将用户重定向到主页,如果未登录并想要访问其他页面,我想将用户重定向到登录页面。有些页面被排除在外,这意味着不需要登录,所以我的代码就在下面:

router.beforeEach((to, from, next) => { 
    if( 
        to.name == 'About' || 
        to.name == 'ContactUs' || 
        to.name == 'Terms' 
    ) 
    { 
        next(); 
    } 
    else 
    { 
        axios.get('/already-loggedin') 
            .then(response => { 
                // response.data is true or false 
                if(response.data) 
                { 
                    if(to.name == 'Login' || to.name == 'Register') 
                    { 
                        next({name: 'Home'}); 
                    } 
                    else 
                    { 
                        next(); 
                    } 
                } 
                else 
                { 
                    next({name: 'Login'}); 
                } 
            }) 
            .catch(error => { 
                // console.log(error); 
            }); 
    } 
}); 

但问题是它进入了一个无限循环,例如每次登录页面加载而用户未登录时,它会将用户重定向到登录页面并再次重定向到登录页面......

我怎样才能解决这个问题?

请您参考如下方法:

这就是我正在做的事情。首先我使用 meta路线的数据,所以我不需要手动放置所有不需要登录的路线:

routes: [ 
  { 
    name: 'About' // + path, component, etc 
  }, 
  { 
    name: 'Dashboard', // + path, component, etc 
    meta: { 
      requiresAuth: true 
    } 
  } 
] 

然后,我有一个像这样的全局守卫:

router.beforeEach((to, from, next) => { 
  if (to.matched.some(record => record.meta.requiresAuth)) { 
    // this route requires auth, check if logged in 
    // if not, redirect to login page. 
    if (!store.getters.isLoggedIn) { 
      next({ name: 'Login' }) 
    } else { 
      next() // go to wherever I'm going 
    } 
  } else { 
    next() // does not require auth, make sure to always call next()! 
  } 
}) 

在这里,我存储用户是否登录,而不是发出新请求。

在您的示例中,您有 忘记了包括 Login进入“不需要身份验证”的页面列表。因此,如果用户试图去假设 Dashboard ,您提出请求,结果他没有登录。然后他转到 Login ,但您的代码检查,发现它不是 3“不需要身份验证”列表的一部分,并进行另一个调用:)

因此跳过这个“列表”是至关重要的! ;)

祝你好运!


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!