3

I have a vuex store and i'd like to apply code splitting on it.

Following this tutorial I tried this:

import Vuex from 'vuex'
import Vue from 'vue'
import createLogger from 'vuex/dist/logger'

Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'

const store = new Vuex.Store({
  strict: debug,
  plugins: debug ? [createLogger] : [],
  state: {
    loading: false
  },
  mutations: {
    toggleLoading: (state) => {
      state.loading = !state.loading
    }
  },
  getters: {
    loading: state => state.loading
  },
  actions: {
    toggleLoading: ({commit}) => {
      commit('toggleLoading')
    }
  }
})

import('./modules/userModule').then(userModule => {
  store.registerModule('user', userModule)
})
import('./modules/tenantsModule').then(tenantsModule => {
  store.registerModule('tenants', tenantsModule)
})
import('./modules/updatesModule').then(updatesModule => {
  store.registerModule('updates', updatesModule)
})

export default store

But the application fails :

webpack-internal:///24:739 [vuex] unknown getter: user

What am i doing wrong?

3
  • That error would appear if you were trying to access the user getter, which you haven't defined. Either by this.$store.getters.user or mapGetters(['user']). Do you access a getter like that anywhere else in your code? Commented Jul 27, 2017 at 13:20
  • @thanksd - I did define it, and it works if i don't use code splitting. I'm guessing it has something to do with the fact that it now loads the modules async. Commented Jul 27, 2017 at 13:55
  • Ahhh ok, you're defining it in your user module. I understand now. Yes, it's definitely because that module hasn't been loaded at the time you're trying to access it. Not sure what the solution is though... Commented Jul 27, 2017 at 14:00

1 Answer 1

1

If are using export default in your modules you need to access it through dot notation (something I read here under 4.2). So something like the below worked for me:

import('./modules/userModule').then(userModule => {
    store.registerModule('user', userModule.default)
})

However, I had some issues with this approach. I often use the store on an initial page load and by then the module hasn't been loaded yet. So I register the part of the store that I need initially directly when declaring the store, like so:

import userModule from './modules/userModule'

Vue.use(Vuex);

export default new Vuex.Store({
    modules: {userModule}
})

Hope this helps!

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.