Javascript Vue路由器未看到存储状态

Javascript Vue路由器未看到存储状态,javascript,vue.js,single-page-application,vuex,vue-router,Javascript,Vue.js,Single Page Application,Vuex,Vue Router,我的Vue应用程序正在使用Vue路由器和vuex。我从API中获得一个身份验证令牌,并将令牌推送到本地存储和我的存储。当页面刷新时,应用程序正在从localStorage加载令牌并将其推送到store。在我的路由器中,我创建了guard: router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.auth)) { if (store.getters.log

我的Vue应用程序正在使用Vue路由器和vuex。我从API中获得一个身份验证令牌,并将令牌推送到本地存储和我的存储。当页面刷新时,应用程序正在从localStorage加载令牌并将其推送到store。在我的路由器中,我创建了guard:

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.auth)) {
        if (store.getters.logged) {
            if (to.meta.scope === store.getters.scope){
                next();
                return;
            }else{
                next({name: 'forbidden'});
                return;
            }
        }
        next({name: 'login'});
    } else {
        next();
    }
});

但防护无法正常工作,因为vue路由器在vuex之前加载,所以存储为空,并且我的作用域未定义。防护将所有请求重定向到禁止。如何解决此问题?

看起来此问题是在从localStorage保存\检索存储的实现中出现的。我建议您不要重新发明轮子,而是使用这个可以解决您问题的软件包:

import createPersistedState from 'vuex-persistedstate'

const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState()]
})