【问题标题】:Vuex module not accessible from rootState无法从 rootState 访问 Vuex 模块
【发布时间】:2018-07-26 05:40:30
【问题描述】:

我需要在 Vuex 中获取路由的查询参数,以便预加载过滤器设置并更新应用程序的状态。为了使这成为可能,我安装了vuex-router-sync

下一步是同步 Vuex 和 VueRouter。

路由器:

Vue.use(VueRouter);
export default new VueRouter({ mode: 'history' });

商店:

Vue.use(Vuex);
export default new Vuex.Store({
    modules: { filters: FiltersModule },
    plugins: [ FiltersPlugin ]
});

应用程序的引导程序:

const unsync = sync(store, router);
new Vue({
    el: '#restaurant-admin-app',
    components: {
        'App': AppComponent,
        'filters': FilterComponent,
        'orders-table': OrdersTableComponent
    },
    store,
    router
});

我的FilterPlugin 应该会触发 URL 解析:

export default store => {
    store.dispatch('filters/parseURLFilterSettings');
}

现在,有趣的部分是 URL 解析操作:

parseURLFilterSettings: ({ state, commit, rootState }) {
    console.log('RootState:',                rootState);
    console.log('Route module (incorrect):', rootState.route);
    console.log('Filters module (correct):', rootState.filters);
    console.log('Object\'s keys:',           Object.keys(rootState));
}

我做错了什么?我认为这可能与同步有关,但最后 console.log 清楚地显示路由对象在那里(并且它不是空的),但是当我访问它时,它是undefined。提前谢谢你。

【问题讨论】:

    标签: vue.js vuejs2 vue-router vuex vuex-modules


    【解决方案1】:

    这个问题已经很好地解释了here。它基本上说的是,当您在控制台中打开它的主体时,会评估对象的值。

    问题是我还没有加载 route 模块,因为我试图从一个似乎在 vuex-router-sync 同步完成之前加载的 vuex 插件中分派一个动作。

    当我将应用程序的引导逻辑从 vuex 插件移动到 AppRootComponent 的挂载生命周期事件时,问题得到了解决。

    【讨论】:

      【解决方案2】:

      您应该导入路由器同步。之后,您的商店和路线将正常运行。我通常在main.js 文件中执行此操作。

      import router from './router'
      import store from './store'
      import { sync } from 'vuex-router-sync'
      
      sync(store, router)
      

      【讨论】:

      • 当然是进口的。我只是不希望这个问题因为进口而有 2,000 行。但是,谢谢。
      猜你喜欢
      • 2017-06-29
      • 2017-10-01
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      • 2017-05-12
      • 2021-09-04
      • 1970-01-01
      • 2020-02-05
      相关资源
      最近更新 更多