我有授权检查码并且有效。现在我需要对未经授权的用户实施路径保护。
问题是存储中的函数没有时间执行,因为它已经需要沿着路径走。
AuthState
和 LoginStatus
尝试从
getters
开始,获取实际状态并尝试从状态获取数据,但什么也没发生
当我重新加载页面或清除缓存时,一切都会重置
//STORE
// call it first from app in created()
state: () => ({
isAuthReady: null,
}),
async AuthState({ dispatch }) {
await auth.onAuthStateChanged((userFirebase) => {
dispatch("LoginStatus", userFirebase);
});
},
LoginStatus({ commit, dispatch }, user) {
//console.log(user)
if (user) {
commit("setAuthReady", true);
commit("setUser", user);
dispatch("UserProfile", user);
dispatch("isAdmin");
} else {
// User is signed out
// ...
}
},
//ROUTER
{
path: "/admin",
component: () => import("@/pages/adminPage/admin"),
meta: { requiresAuth: true },
}
router.beforeEach(async (to, from, next) => {
if (to.meta.requiresAuth) {
if (store.state.user.userInfo.length || store.state.user.userInfo.id) {
next();
} else {
await store.dispatch("auth/openLoginForm");
next("/");
}
} else next();
});
我不知道我做得是否正确,但正如这个Answer中所建议的,我认为这在firebase中是可能的。
router.beforeEach((to, from, next) => {
auth.onAuthStateChanged(async (userFirebase) => {
if (to.meta.requiresAuth) {
if (userFirebase) {
next();
} else {
await store.dispatch("auth/openLoginForm");
next("/");
}
} else next();
});
});
不知道你还需要吗,但我就是这样用的
router.beforeEach(async (to, from) => {
await auth.authStateReady();
if (to.meta.requiresAuth && !auth.currentUser) {
return {
path: "/",
query: { redirect: to.fullPath },
};
}
});