vue js 路由器 + firebase 身份验证

vue js router + firebase authentication

我使用 vue js 2.4.2vue router 2.7.0firebase 4.3.0。我无法让路由身份验证工作。这是我现在的 route.js

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)

import Firebase from './firebase'

import Dashboard from './components/Dashboard.vue'
import Auth from './components/Auth.vue'


let router = new Router({
    mode: 'history',
    routes: [
        {
            path: '/',
            component: Dashboard,
            meta: {
                auth: true
            }
        },
        {
            path: '/login',
            component: Auth
        }
    ]
})

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.auth)) {
        if (!Firebase.auth().currentUser) {
            next({
                path: '/login'
            })
        } else {
            next()
        }
    } else {
        next()
    }
})

export default router

但现在每次我去 / 它都会将我重定向回 /login,可能是因为 Firebase.auth().currentUsernull,即使我实际上已经登录了. 我该如何解决这个问题?

尝试使用 Firebase.auth().onAuthStateChanged 而不是 Firebase.auth().currentUser;这是获取当前用户的推荐方式。

通过 currentUser 获取用户可能会导致类似于您所看到的问题。这是来自firebase的官方文档。

Note: currentUser might also be null because the auth object has not finished initializing. If you use an observer to keep track of the user's sign-in status, you don't need to handle this case.

尝试像这样设置您的身份验证逻辑:

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.auth)) {
        Firebase.auth().onAuthStateChanged(function(user) {
            if (!user) {
                next({
                    path: '/login'
                })
            } else {
                next()
            }
        }
    } else {
        next()
    }
})