我使用vue js 2.4.2
,vue router 2.7.0
和firebase 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().currentUser
是null
,即使我实际登录了。我能解决这个问题吗?
答案 0 :(得分:0)
尝试使用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()
}
})