0
votes

I started out using Vuex and as it got crowded in the store.js, I added modules.
My modules state and getters look fine in Vue Tools when I inspect the Vuex store but all the base store getters and state are undefined and I can't seem to tell why. I import the base store as import store from '../store/store' in the app.js file. Any ideas on what I'm doing wrong here?

my base store looks like this:

store.js

import Vuex from 'vuex';
import Vue from 'vue';
import axios from "axios";
import { users } from './users-store';

Vue.use(Vuex);

const initialState = () => ({
    state: {
        letters: null,
        names: false,
    },
});

const state = initialState();

const getters = {
    getLetters(state) {
        return state.letters;
    },
    getNames(state) {
        return state.names;
    },
    
};

const mutations = {
    setLetters: (state,payload) => {
        state.letters = payload;
    },
    setNames: (state,payload) => {
        state.names = payload;
    },
};

export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters,
    modules: {
        users
    },
});

users-store.js

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

Vue.use(Vuex);

const initialState = () => ({
    userName: null,
    userAge: 50
});

const state = initialState();

const mutations = {
    setUserName: (state,payload) => {
        state.userName = payload;
    },
    setUserAge: (state,payload) => {
        state.userAge = payload;
    },

};

const getters = {
    getUserName(state) {
        return state.userName;
    },
    getUserAge(state) {
        return state.userAge;
    },
};


export const users = {
    namespaced: true,
    state,
    mutations,
    getters,
    actions,
};
1

1 Answers

1
votes

I usually do it just like the docs for modular store:

Please note the comments

store/index.js:

import Vue from 'vue'
import Vuex from 'Vuex'
import ModuleA from './modules/module-a.js'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {}, // with object, not a function returning object
  getters: {},
  mutations: {},
  actions: {},
  modules: {
    ModuleA,
  },
})

export default store

store/modules/module-a.js:

const ModuleA = {
  state: () => ({}), // a function for this one
  getters: {},
  mutations: {},
  actions: {}
}

export default ModuleA // and I use default export instead of named export

And it works out great.

Note that I use latest versions of Vue and Vuex on this.