3

I have a fairly large VueJS SPA, and I just wanted to load the vuex modules on certain routes, using the lazy load.

I was following this article to reproduce this - https://alexjoverm.github.io/2017/07/16/Lazy-load-in-Vue-using-Webpack-s-code-splitting/

However this is giving me an error in vuex.

Folder structure

root
  |- store
  | |- modules
  | | |- auth.js
  | | |- module2.js
  | |- store.js
  |- app.js

auth.js

const state = {
    var1: {},
    var2: false
}

const mutations = {
    'MUTATION_1'(state, obj) {
        // logic
    }
}

const actions = {
    action1({commit}) {
       // logic
    }
}

const getters = {
    var1: state => state.var1,
    var2: state => state.var2
}

export default {
    state,
    mutations,
    actions,
    getters
}

store.js -

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

Vue.use(Vuex);
const store = new Vuex.Store();

import('./modules/auth.js').then(auth => {
    store.registerModule('/login', auth);
});

export default store;

app.js -

import Vue from 'vue';
import store from './store/store';
import VueRouter from 'vue-router';
import { routes } from './routes/routes';

// vue-router config
Vue.use(VueRouter);

const router = new VueRouter({
    mode: 'history',
    routes
});

const app = new Vue({
    el: '#app',
    store,
    router
});

error -

[vuex] unknown getter: var1

Any suggestion?

2 Answers 2

5
store.registerModule('/login', auth);

The above code registers the auth module with the namespace of login so in order to access its state, getters, mutations, and actions from the store you have to prefix all of those with the path login/. You got the error because you probably tried store.getters.var1 when you should have called store.getters['login/var1'].

Sign up to request clarification or add additional context in comments.

Comments

2

Getter is called before the login module was loaded. This happens because import() is asynchronous function, and the module was registered sometime after computed watcher was created. return store.state.login && store.getters['login/var1'] inside component computed getter will subscribe your component to store.state changes first, then after login module loaded and registered store.state will change and trigger component computed getter and automatically subscribe to any state.login changes

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.