首页 > 解决方案 > 在 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 它和它的真实

标签: async-awaitvuexactionvue-router

解决方案


我已经找到了解决方案。也许它会帮助某人:

我创建了一个 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);
        });
    },





 

推荐阅读