[英]use firebase auth with vue 3 route guard
我需要將 firebase auth 與 vue 路由器一起使用。
我有這個簡單的守衛,但我注意到有時如果用戶沒有登錄,他們也會看到一段時間的頁面。
router.beforeEach( async (to, from) => {
onAuthStateChanged( getAuth(app), (user) => {
console.log(user, to.meta.requireAuth)
if( to.meta.requireAuth && !user ) {
return {
name: 'Signin'
}
}
})
})
我的組件內部也有這種控制,但我正在尋找全局的東西來防止未注冊的用戶看到該應用程序。
有什么建議嗎?
您可以將 onAuthStateChanged 包裝在 Promise 中,並在每個之前設置一個異步函數。
// in some global file
export async function getCurrentUser(): Promise<User | null> {
return new Promise((resolve, reject) => {
const unsubscribe = auth.onAuthStateChanged((user) => {
unsubscribe();
resolve(user);
}, reject);
});
}
// your router file
router.beforeEach(async (to, from, next) => {
if (to.matched.some((record) => record.meta.publicAccess)) {
next();
} else {
const currentUser = await getCurrentUser();
if (currentUser) {
next();
} else {
next({ name: "Login" });
}
}
});
// Your route object
{
name: "Login",
path: "/login",
component: () => import("@/views/authentication/Login.vue"),
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.