Vue导航守卫在直接访问URL时重定向



我正在尝试设置Vue导航守卫。如果使用Firebase Auth进行身份验证,我的一个守卫将用户从Index组件重定向到Dashboard组件。

如果我通过另一个组件的路由器链接导航到Index页面,它会很好。但是,如果我通过在浏览器中直接键入URL转到Index页面,它不会正确地重定向用户。

无论用户如何访问路由,我如何实现此重定向?

const routes = [
  {
    path: '/',
    name: 'Index',
    component: () => import('../components/Index.vue'),
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../components/Dashboard.vue')
  }
]
router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const isAuthenticated = firebase.auth().currentUser
  if(isAuthenticated && to.path === '/') {
    console.log(to.path);
    next('/dashboard')
  }
})

我也尝试了单独定义的路由上的beforeRouteEnter,但这也不起作用。

这是因为在您从firebase获取用户数据之前,您的导航守卫被调用了。此时,firebase.auth()。

当前用户是空的,就好像你没有经过身份验证。看看这个解决方案。它非常优雅,解决了你的问题。

最新更新