我想使用导航卫士,但是我的商店数据是异步的并且一直到很晚,所以beforeEach在加载我的身份验证状态之前运行。我试图将我的身份验证状态加载到vue应用程序的created()挂钩中,然后尝试在before.Each运行之前在main.js或router.js中在新Vue之前加载它。诺言...
这是我的异步操作
export default {
async setIsAuthenticated(context) {
await auth.onAuthStateChanged(function(user) {
if (user) {
context.commit('setIsAuthenticated', true);
context.dispatch('user/setUserData', user.uid, {
root: true,
});
}
});
}
setIsAuthenticated操作触发了此突变
setIsAuthenticated(state, payload) {
state.isAuthenticated = payload;
},
这是我的router.js beforeEach()
router.beforeEach((to, from, next) => {
if (to.path !== '/userauth' && !store.getters['auth/isAuthenticated']) {
next('/userauth'):
} else {
next();
}
我试图在等待诺言的情况下派遣它
store.dispatch('auth/setIsAuthenticated').then(log => {
console.log(log);
});
console.log(store.getters['auth/isAuthenticated']);
但是isAuthenticated始终为null。只有当网站完全加载后,我才能console.log它及其真实的
答案 0 :(得分:0)
我已经找到了解决方案。也许会帮助某人:
我创建了一个init操作,该操作返回一个promise,并分派我的操作,在执行其他任何操作之前,该操作会先获得身份验证状态。
store.dispatch('init').then(() => {
new Vue({
vuetify,
router,
store,
render: h => h(App),
}).$mount('#app');
});
这是动作初始化:
actions: {
init(context) {
return new Promise(resolve => {
setTimeout(() => {
context.dispatch('auth/setIsAuthenticated', null, {
root: true,
});
resolve('Done');
}, 1000);
});
},