【问题标题】:Vue router have not seen store stateVue路由器还没有看到商店状态
【发布时间】:2020-01-16 17:47:27
【问题描述】:

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

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-router 在 vuex 之前加载,所以防护无法正常工作,因此存储为空且我的范围未定义防护将所有请求重定向到禁止。我该如何解决这个问题?

【问题讨论】:

    标签: javascript vue.js single-page-application vuex vue-router


    【解决方案1】:

    看起来这个问题是在从 localStorage 保存\检索存储的实现中。我建议你不要重新发明轮子,而是使用这个包来解决你的问题:
    https://www.npmjs.com/package/vuex-persistedstate

    import createPersistedState from 'vuex-persistedstate'
    
    const store = new Vuex.Store({
      // ...
      plugins: [createPersistedState()]
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-01
      • 2018-02-12
      • 2020-09-27
      • 1970-01-01
      • 2019-01-25
      • 2022-01-09
      • 2018-06-24
      • 2017-08-07
      相关资源
      最近更新 更多