首页 > 解决方案 > vuejs - 如果已经登录,则从登录/注册重定向到主页,如果未在 vue-router 中登录,则从其他页面重定向到登录

问题描述

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

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);
            });
    }
});

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

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

标签: vue.jsvue-router

解决方案


这就是我正在做的事情。首先我使用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“不需要身份验证”列表的一部分,并制作另一个电话:)

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

祝你好运!


推荐阅读