【问题标题】:vuex persisted state not working with vue router navigation guardvuex 持久化状态不适用于 vue 路由器导航防护
【发布时间】:2019-03-18 21:39:33
【问题描述】:

我已按照文档中的定义添加了 vuex-persistedstate(已确认且有效)

export default new Vuex.Store({
    modules: {
        auth,
    },
    plugins: [VuexPersistedState()]
});

我已经设置了一个路由器导航保护,以便在登录时重定向到主页

/* Auth based route handler */
router.beforeEach((to, from, next) => {
    if (to.meta.hasOwnProperty('requiresAuth')) {
        if (to.meta.requiresAuth === true) {
            let isAuthenticated = authStore.getters.isAuthenticated
            if (isAuthenticated(authStore.state) === true) {
                next()
            } else {
                next({name: 'login'})
            }
        } else {
            let isAuthenticated = authStore.getters.isAuthenticated
            console.log(authStore.state)
            if (isAuthenticated(authStore.state) === true) {
                next({name: 'home'})
            } else {
                next()
            }
        }
    } else {
        next()
    }
})

vuex 持久化状态从本地存储恢复存储,但不是在导航守卫之前!

我可以提供源代码的任何必要部分进行评估。请根据需要评论您的请求。也欢迎实验性解决方案。这对我来说只是一个个人培训应用程序!

感谢您的帮助!

【问题讨论】:

  • vuex 和 vue-router 的 Vue.use() 的相对顺序是什么?您可能想尝试翻转它(第一次切割)。
  • 我无法重现您的问题。事实上,看起来 vue-router 和 vuex 的相对顺序甚至都没有关系。你会尝试将商店的状态发送给 getter,而 getter 本身可以访问商店,这对我来说看起来很奇怪,所以也许那里发生了一些奇怪的事情?
  • 在没有计算范围的情况下直接访问 getter 不会传递带有状态的 getter。从 store 对象访问 getter 就像从文件访问导出的函数一样。因此,以这种方式调用 getter 会将状态对象分配为未定义。因此我需要传递状态对象。

标签: vue.js vuejs2 vuex vue-router


【解决方案1】:

我知道这可能对@Vaishnav 没有用,但是由于我最近没有进入同一个兔子洞,我想我会发布一个我在这里找到的解决方法,因为这是我发现的唯一一个询问的帖子专门针对这个问题。

在您的store/index.js 中,您需要同时导出函数和存储对象。

改变这个:

export default() => {
  return new vuex.Store({
  namespaced: true,
  strict: debug,
    modules: {
      someMod 
    }, 
    plugins: [createPersistedState(persistedStateConfig)] 
  }); 
};

到:

const storeObj = new vuex.Store({
  namespaced: true,
  strict: debug,
  modules: {
    someMod
  },
  plugins: [createPersistedState(persistedStateConfig)]
});

const store = () => {
  return storeObj;
};

export {store, storeObj}

然后,由于您现在更改了导出商店的方式,因此您还需要更改导入方式。

在您的应用中您已导入商店的任何地方,即:main.js -> import store from '@/store' 不包括 router.js,您需要更改为 import {store} from '@/store'

在您的router.js 中只需import {storeObj} from '@/store' 并在路由器保护中使用它而不是store 即:storeObj.getters['someMod/someValue']

【讨论】:

  • 但是状态的箭头函数实现确实使它在突变时动态变化吗?我解决了这个问题,发现状态实际上并没有改变,因此在 Vuex 文档中提供了如何全局使用 store 的解决方案。
【解决方案2】:

我找到了一个工作示例。

因为路由器不是一个组件。

在路由器配置文件中 -

罢工>

import authStore from '@/stores/auth/store'

相反 -

import store from '@/store'

在导航守卫中,我替换了

罢工>

let isAuthenticated = authStore.getters.isAuthenticated
if(isAuthenticated(authstore.state) === true){...}

与 -

let isAuthenticated = store.getters['auth/isAuthenticated']
if(isAuthenticated === true){...}

现在这个工作就像魅力......

【讨论】:

    猜你喜欢
    • 2020-03-13
    • 2021-04-24
    • 2022-09-27
    • 2021-05-04
    • 1970-01-01
    • 2019-11-11
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多