Vue + Firebase路由,防止用户登录后返回登录页面



我使用VueJS 3和firebase开发SPA。我想阻止用户登录后访问登录页面。但在尝试不同的代码后,路由似乎保持循环或错误。

的路线:

{
path: '/', name: 'login', component: () => import('../views/LoginView.vue')
},
{
path: '/dashboard', name: 'dashboard', component: () => import('../views/DashboardView.vue'),
meta: {
requiresAuth: true,
},
},

逻辑(没有显示任何内容):

const getCurrentUser = () => {
return new Promise((resolve, reject) => {
const removeListener = onAuthStateChanged(
getAuth(),
(user) => {
removeListener()
resolve(user)
},
reject
)
})
}
router.beforeEach(async (to, from, next) =>{
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (await getCurrentUser()) {
next()
} else {
next("/")
}
} else {
next("/dashboard")
} 
})

这个继续循环:

router.beforeEach(async (to, from, next) =>{
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (await getCurrentUser()) {
next()
} else {
next("/")
}
} 
next("/dashboard")
})

正如Vue路由器文档中提到的:

必须调用"next"在任何给定的情况下,只能通过一次导航守卫。它可以出现多次,但前提是逻辑路径没有重叠,否则钩子永远不会被解析或产生错误。:

他们提供了这些例子:

// BAD
router.beforeEach((to, from, next) => {
if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
// if the user is not authenticated, `next` is called twice
next()
})
// GOOD
router.beforeEach((to, from, next) => {
if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
else next()
})

同时,确保没有无限循环:

next("/dashboad")强制重定向到Dashboard页面,无论我们来自哪个页面。你可能会在一个循环中结束,每个页面都重定向到仪表盘,包括仪表板页面本身

最新更新