Adri
Adri

Reputation: 365

Lazy loading on vuex modules

I’m trying to use lazy loading with my vuex modules like this article : https://alexjoverm.github.io/2017/07/16/Lazy-load-in-Vue-using-Webpack-s-code-splitting/

Here is my old store\index.js :

import Vue from 'vue';
import Vuex from 'vuex';

import app from './modules/app';
import search from './modules/search';
import identity from './modules/identity';
import profil from './modules/profil';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    app,
    search,
    identity,
    profil,
  },
});

I tried to do this :

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store();

import('./modules/app').then((appModule) => {
  store.registerModule('app', appModule);
});

import('./modules/search').then((searchModule) => {
  store.registerModule('search', searchModule);
});

import('./modules/identity').then((identityModule) => {
  store.registerModule('identity', identityModule);
});

import('./modules/profil').then((profilModule) => {
  store.registerModule('profil', profilModule);
});

export default store;

But now I have a lot of error like “TypeError: _vm.consultList is undefined", consultList is a mapState variable, I also have same errors on my mapActions Did I’ve done something wrong ?

Upvotes: 5

Views: 2495

Answers (1)

Jeremy Walters
Jeremy Walters

Reputation: 2152

All of those modules will be registered when app is loaded any because you most likely add the store to your initial vue instance. How I dynamically loading my vuex module is via the router:

{
            path: "/orders/active",
            name: "active-orders",
            component: ActiveOrders,
            props: true,
            beforeEnter: (to, from, next) => {
                importOrdersState().then(() => {
                    next();
                });
            }
        },

Then also inside my router file I added:

const importOrdersState = () =>
    import("@/store/orders").then(({ orders }) => {
        if (!store.state.orders) store.registerModule("orders", orders);
        else return;
    });

Upvotes: 7

Related Questions