async-await - 在 vue-router 运行 beforeEach 之前访问异步存储数据(导航守卫)
问题描述
我想使用导航保护,但我的存储数据是异步的,而且它总是很晚,所以 beforeEach 在我的身份验证状态加载之前运行。我尝试在我的 vue 应用程序的 created() 挂钩中加载我的身份验证状态,然后我尝试在 main.js 中的新 Vue 之前或在 beforeEach 运行之前在 router.js 中加载它......我什至尝试过等待承诺...
这是我的异步操作
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 始终为空。只有当网站完全加载时,我才能 console.log 它和它的真实
解决方案
我已经找到了解决方案。也许它会帮助某人:
我创建了一个 init 操作,它返回一个承诺并分派我的操作,在我做任何其他事情之前让我获得身份验证状态。
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);
});
},
推荐阅读
- c# - 当我下载太快时,C# Webclient().OpenRead 是连接返回 404 错误
- c++ - 读取 HDFql 中的属性值
- ios - 错误的服务器端验证 Apple 的应用内购买 (IAP)
- objective-c - 如何在多页 NSPrintOperation 中更改页面方向?
- laravel - 解析器是对 Graphql 进行困难查询的最佳实践?
- javascript - 基于第一个数组比较两个数组,然后返回匹配甚至不精确的值
- c++ - 以相反的顺序连接两个链表
- c# - 如何扩展模型以填充网格而不在保存时验证外键?
- android - Flutter PlatformViews:尝试创建未注册类型的平台视图
- matlab - 如何让matlab在给出结果之前简化方程