![](/img/trans.png)
[英]how can I keep a user looged in even after page reload in nextjs app with firebase authentication?
[英]How to fix reloading issue of authentication on page reload reload, Firebase and Vuejs
当前,当我重新加载仪表板时,首先将其重定向到/ login,然后如果用户已经登录,则重定向到/ dashboard。 它看起来很有线。 如果用户登录,我该如何解决,使其直接进入/ dashboard。
在main.js中创建的函数
created: function() {
try {
firebase.initializeApp(firebaseConfig);
}
catch(error){
return;
}
const store = this.$store;
firebase.auth().onAuthStateChanged(function(user){
if(typeof user !== 'undefined' && user !== null){
store.dispatch('loginUserOnLoad', user);
}
});
}
LoginUserOnlOad操作
loginUserOnLoad: function({ commit }, user){
commit('authUser',{
email: user.email,
fullname: 'Guest'
})
},
这是完整的路由器配置,
Vue.use(Router);
const router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Welcome',
component: Welcome
},
{
path: '/tasks',
name: 'Tasks',
component: Layout,
meta: {
requireAuth: true
}
},
{
path: '/login',
name: 'Login',
component: Signin,
meta: {
guestAuth: true
}
},
{
path: '/register',
name: 'Signup',
component: Signup,
meta: {
guestAuth: true
}
},
{
path: '*',
name: 'NotFound',
component: NotFound
}
]
});
router.beforeEach((to, from, next) => {
const currentUser = firebase.auth.currentUser;
const requireAuth = to.matched.some(record => record.meta.requireAuth);
if(requireAuth && !currentUser){
next({ name: 'Login'});
}
else if(!requireAuth && currentUser){
next({ name: 'Tasks'});
}
else {
next();
}
});
export default router;
我不知道如何配置和导出Firebase,但我认为您应该按以下方式修改路由器代码(请参阅代码中的注释):
router.beforeEach((to, from, next) => {
//Instead of const currentUser = firebase.auth.currentUser; do
const currentUser = firebase.auth().currentUser;
const requireAuth = to.matched.some(record => record.meta.requireAuth);
if(requireAuth && !currentUser){
next({ name: 'Login'});
}
else if(!requireAuth && currentUser){
next({ name: 'Tasks'});
}
else {
next();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.