问题在于,vue-router的beforeEnter早于main.js中的beforeCreate钩子触发,并且具有第二个延迟,而在重新加载vuex操作之后,将用户置于状态。这导致用户跳回登录页面。
如何延迟vue-router的beforeEnter检查,直到vuex将授权用户设置为状态。
router.js
[vuex] unknown action type: FETCH_LABEL
auth.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from '../views/Home.vue'
import auth from './auth'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/reservations',
name: 'Reservations',
component: () => import('@/views/Reservation/Reservations.vue'),
beforeEnter: auth
}
]
})
main.js
import { store } from "../store";
export default (to, from, next) => {
if(store.getters.user) {
next()
} else {
console.log('auth')
next('/signin')
}
}
store / user.js
import Vue from 'vue'
import App from './App.vue'
import router from './router/router'
import {store} from './store'
import firebase from 'firebase/app'
import 'firebase/app'
import config from './config'
new Vue({
router,
store,
render: h => h(App),
beforeCreate() {
firebase.initializeApp(config).firestore().settings({timestampsInSnapshots: true})
console.log('main')
this.$store.dispatch('authCheck')
}
}).$mount('#app')
在控制台中,我首先从beforeEnter检查中看到“ auth”,然后从beforeCreate中看到“ main”。如何在路由器检查之前触发“ authCheck”
答案 0 :(得分:0)
在您的auth.js文件中,而不是监视商店,您应该等待authStateChanged
事件,然后在从firebase接收用户时进行处理。
auth.js
export default (to, from, next) => {
firebase.auth().onAuthStateChanged(function (user) {
if (user)
next();
else
next('/signin');
});
}