【问题标题】:vue js router + firebase authenticationvue js 路由器 + firebase 身份验证
【发布时间】:2018-02-04 15:25:06
【问题描述】:

我使用 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 ?

标签: firebase vue.js firebase-authentication vue-router


【解决方案1】:

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

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

注意:currentUser 也可能为 null,因为 auth 对象尚未完成初始化。如果您使用观察者来跟踪用户的登录状态,则无需处理这种情况。

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

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()
    }
})

【讨论】:

    猜你喜欢
    • 2017-09-24
    • 2018-04-13
    • 2021-11-07
    • 1970-01-01
    • 2017-05-05
    • 2018-07-07
    • 2020-07-14
    • 2015-11-30
    • 1970-01-01
    相关资源
    最近更新 更多