簡體   English   中英

如何解決頁面重新加載,Firebase和Vuejs上身份驗證的重新加載問題

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM