我想重定向用户到主页,如果登录,并希望访问登录/注册页面,并重定向用户到登录页面,如果没有登录,并希望访问其他页面.有些页面被排除在外,这意味着不需要登录,因此我的代码如下所示:

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"auth not required"列表的一部分,并再次调用:)

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

祝你好运

Vue.js相关问答推荐

获取深度嵌套对象时无法读取空/未定义的属性

混合使用 React 和 Vue 是个好主意吗?

实现登录命令并访问 vuex 存储

为什么在 Vue.js 中使用 `var` 关键字?

在 vue 3 中使用 vue-chartjs:createElement 不是函数

确保在渲染组件之前加载 Vuex 状态

如何为 Vue 应用提供 robots.txt

为什么 Vue 路由/Webpack 开发服务器现在在页面刷新时显示无法获取/路径?

为什么 CSS 关键帧动画在具有范围样式的 Vue 组件中被 destruct ?

将自定义部分添加到 v-autocomplete 下拉列表

如何在nuxt路由中添加meta?

即使在客户端设置 Access-Control-Allow-Origin 或其他 Access-Control-Allow-* 标头后也出现 CORS 错误

在 Vue.js 中,为什么我们必须在导入组件后导出它们?

Vuetify 2 个工具栏和 1 个导航抽屉,navigation drawer导航抽屉上方有 1 个工具栏

Nuxt 应用程序在刷新动态路由时返回 404(Tomcat 服务器)

Vue CLI - 将构建输出组合到单个 html 文件

Nuxt.js - API 调用的最佳场所

vuejs 配置:使用全局变量?

何时使用

更改事件上的 Select2 在 Vuejs 中不起作用