Vuex Modules in Multiple Files in NuxtJS

July 3rd 2020 NuxtJS Vuex Vue.js

One of the options for creating a Vuex module in NuxtJS is to create separate state.ts, getters.ts, mutations.ts, and actions.ts files in the module folder. Especially for large modules, this can make the code easier to navigate. However, a very important detail about this approach is mentioned very briefly in the documentation.

I missed that detail and after I tried out my newly implemented Vuex module for the first time, I was greeted by the following error:

[vuex] getters should be function but "getters.getters" is {}.

It took me a while to figure out that the error was thrown because my export of getters didn't match what NuxtJS expected:

// wrong
export const getters = {
  isDefault: (state: RootState) => state.count === 0,

// correct
const getters = {
  isDefault: (state: RootState) => state.count === 0,
export default getters;

The important part is that the getters object has to be the default export from the file. Exports of the state, mutations, and actions from the other files have the same requirement. They must all be the default export from their corresponding file. Otherwise, you can expect errors similar to the one for getters:

store/state.ts should export a method that returns an object

[vuex] mutations should be function but "mutations.mutations" is {}.

[vuex] actions should be function or object with "handler" function but "actions.actions" is {}.

If you want to try it out for yourself, check the sample application from my GitHub repository. The latest commit features a working store and the one before that a broken one.

NuxtJS supports having separate files for the state, getters, mutations, and actions of a Vuex module. But they must all be default exports in the corresponding files.

If you're looking for online one-on-one mentorship on a related topic, you can find me on Codementor.
If you need a team of experienced software engineers to help you with a project, contact us at Razum.
Creative Commons License