By the end of the previous lesson, Colmena's store worked, but it was already showing signs of disorderly growth: a single file of more than a hundred lines, properties with prefixes (loadingRooms, bookingsError) to tell which part they belong to, and catalogue mutations mixed up with booking mutations. And the session was missing: it is still in the temporary module src/session.js. Vuex modules let you split the store into independent parts, each with its own state, getters, mutations and actions. In this lesson you will see how they are declared, what changes when you enable namespaces (namespaced: true), how a module communicates with the root and with the other modules (rootState, rootGetters, { root: true }), how they are nested and how they are registered on demand. In Colmena you will split the store into the rooms, bookings and session modules, delete src/session.js, and the router's guards will read the session from the store.

Contents

  1. Why split the store
  2. The modules option and local state
  3. Namespaces: namespaced: true
  4. Accessing the root and other modules: rootState and rootGetters
  5. Dispatching and committing outside the module: { root: true }
  6. Nested modules
  7. Dynamic module registration
  8. Folder organisation
  9. Case study: Colmena in three modules

  1. Why split the store

A Vuex store is a single tree of state. That is an advantage (a single source of truth) and, without organisation, a problem: in a medium-sized application, the store file ends up with hundreds of mutations and actions from unrelated domains.

Symptom in a store without modules With modules
Prefixes in the names (loadingRooms, loadingBookings) Each module has its own loading
A huge file that every developer touches at the same time (Git conflicts) One file per domain
To understand the bookings you also have to read the catalogue Each module can be understood on its own
Impossible to load part of the store only when it is needed Dynamic registration (section 7)

Modules do not create several stores: there is still just one store, with one state tree, one timeline and one commit/dispatch. The tree is simply divided into branches.

  1. The modules option and local state

A module is an object with the same options as the store: state, getters, mutations, actions (and, if it wants, its own modules). It is registered with the modules option:

const roomsModule = {
  state: () => ({ list: [], loading: false }),
  mutations: {
    setRooms(state, rooms) {
      state.list = rooms // "state" is the module's LOCAL state
    }
  }
}

const bookingsModule = {
  state: () => ({ list: [], loading: false }),
  // ...
}

const store = createStore({
  modules: {
    rooms: roomsModule,      // the key is the name of the state branch
    bookings: bookingsModule
  }
})

Each module's state hangs from the tree under the name of its key:

store.state.rooms.list     // catalogue
store.state.bookings.list  // bookings
flowchart TD
    R["store.state"] --> S["rooms<br/>{ list, loading, ... }"]
    R --> RE["bookings<br/>{ list, loading, ... }"]
    R --> SE["session<br/>{ name, email, plan, role }"]

Inside the module, everything is local:

  • Mutations and getters receive as state the module's state ({ list, loading }), not the root state. That is why they can be called list and loading without prefixes.
  • In actions, context.state is also the local state.

But, without namespaces, only the state is local. Getters, mutations and actions are registered in the global namespace:

store.commit('setRooms', rooms) // no prefix: the name is global
store.getters.availableRooms    // no prefix

That has a dangerous consequence: if two modules have a mutation with the same name (for example, startLoading), a commit('startLoading') runs both. And two getters with the same name cause a duplicate error. This behaviour exists for compatibility with old code; in new code, you avoid it with the next section.

  1. Namespaces: namespaced: true

With namespaced: true, everything in the module sits under a namespace that matches its key:

const bookingsModule = {
  namespaced: true,
  state: () => ({ list: [] }),
  getters: {
    activeBookings: (state) => state.list.filter((b) => b.status !== 'cancelled')
  },
  mutations: {
    addBooking(state, booking) {
      state.list.push(booking)
    }
  },
  actions: {
    async createBooking({ commit }, data) {
      const created = await apiCreateBooking(data)
      commit('addBooking', created) // INSIDE the module: local name, no prefix
      return created
    }
  }
}

From outside the module, the names carry the module/ prefix:

From outside (components, router, other modules) Inside the module itself
store.state.bookings.list state.list
store.getters['bookings/activeBookings'] getters.activeBookings
store.commit('bookings/addBooking', b) commit('addBooking', b)
store.dispatch('bookings/createBooking', data) dispatch('createBooking', data)

Note two details:

  • Prefixed getters are read with square brackets: store.getters['bookings/activeBookings']. A slash is not valid in a property name accessed with a dot.
  • Nothing changes inside the module: the context an action receives is already "bound" to the namespace, so commit('addBooking') goes to the module's own mutation. This lets you move or rename a module without touching its internal code.

In practice, every module should be namespaced: true. That is what we will do in Colmena.

  1. Accessing the root and other modules: rootState and rootGetters

A module sometimes needs data from another: the amount for the bookings depends on the catalogue's prices. For this, a module's getters and actions receive additional arguments.

In getters, the third and fourth arguments:

getters: {
  // (local state, local getters, root state, root getters)
  monthlyBookingsTotal(state, getters, rootState, rootGetters) {
    const price = rootGetters['rooms/roomById']('nectar')?.hourlyPrice
    // rootState.rooms.list would also be available
  }
}

In actions, as properties of context:

actions: {
  async loadBookings({ commit, rootState, rootGetters }) {
    if (rootGetters['session/active']) {
      // ...
    }
  }
}
Argument In a getter In an action Contents
state 1st context.state The module's state
getters 2nd context.getters The module's getters (no prefix)
rootState 3rd context.rootState The complete state (rootState.rooms.list)
rootGetters 4th context.rootGetters All the getters (rootGetters['rooms/roomById'])

Mutations do not receive rootState: they can only modify their own module's state. If a mutation needs data from another module, the action that commits it reads that data and passes it in the payload.

A design warning: every rootGetters['other/...'] is a dependency between modules. Some are natural (bookings need prices), but if every module reads from every other, you lose the benefit of splitting. Keep dependencies flowing in one direction whenever you can.

  1. Dispatching and committing outside the module: { root: true }

Inside a namespaced module, dispatch('x') and commit('x') refer to the module itself. To reach another module (or the root), you pass a third argument { root: true } and the full name:

actions: {
  async loadBookings({ dispatch }) {
    // An action in ANOTHER module: full name + root: true
    await dispatch('rooms/loadRooms', null, { root: true })
  },

  signOut({ commit }) {
    commit('reset')                                    // own mutation
    commit('bookings/clear', null, { root: true })     // another module's mutation
  }
}
  • The second argument is the payload; if there is none, you pass null (or undefined) so that you can reach the third.
  • Committing another module's mutations (commit('bookings/clear', ..., { root: true })) is possible, but it couples the modules tightly: the one committing knows the internal details of the other. Whenever one exists, it is better to dispatch an action of the other module, which is its public interface. We will use it sparingly.

There is also the reverse operation: registering a global action (without a prefix) from a namespaced module, using the { root: true, handler } form:

actions: {
  resetAll: {
    root: true, // registered as 'resetAll', not as 'bookings/resetAll'
    handler({ commit }) {
      commit('clear')
    }
  }
}

It is uncommon; you will see it in legacy code for actions that several modules listen to under the same name.

  1. Nested modules

A module can have its own modules. The state is nested and, if they are all namespaced, the prefixes are concatenated:

const dashboardModule = {
  namespaced: true,
  state: () => ({ menuOpen: false }),
  modules: {
    preferences: {
      namespaced: true,
      state: () => ({ compactView: false }),
      mutations: {
        toggleCompactView(state) {
          state.compactView = !state.compactView
        }
      }
    }
  }
}

const store = createStore({ modules: { dashboard: dashboardModule } })

store.state.dashboard.preferences.compactView             // nested state
store.commit('dashboard/preferences/toggleCompactView')   // concatenated prefix

If a nested module does not declare namespaced: true, it inherits its parent's namespace (its names would become dashboard/toggleCompactView).

Use nesting with caution. Two levels are reasonable; beyond that, the names become long and the tree hard to navigate. A flat store of well-chosen top-level modules is usually clearer.

  1. Dynamic module registration

The modules declared in createStore are registered when the store is created, and their code goes into the application's main bundle. But there are features that only some users use, such as Colmena's invoicing, which only managers see and whose view is already lazy-loaded (04-02). Its store module can be loaded along with it:

// Register
store.registerModule('billing', billingModule)

// Is it registered?
store.hasModule('billing') // true

// Remove (its state disappears from the tree)
store.unregisterModule('billing')

A common pattern is to register it from the lazy view itself, when it is created:

// DashboardInvoicesView.vue (example)
import { useStore } from 'vuex'
import billingModule from '@/store/modules/billing.js'

const store = useStore()
if (!store.hasModule('billing')) {
  store.registerModule('billing', billingModule)
}

Because billingModule is imported from a file that only this view uses, Vite bundles it into the same lazy chunk as the view: the module's code is not downloaded until a manager opens the invoices.

Things to bear in mind:

Option / case Behaviour
registerModule(['dashboard', 'invoices'], module) Registers a nested module (the parent must exist)
{ preserveState: true } Does not overwrite the state if it already exists in the tree (useful when the state comes from the server, with SSR, or is restored from storage)
Checking hasModule first Registering the same name twice gives a warning and resets the module
unregisterModule on leaving Frees memory, but the state is lost. Decide whether it is worth keeping it for the next visit
Modules declared in createStore Cannot be removed with unregisterModule

  1. Folder organisation

The most widespread structure in projects that use Vuex is one file per module inside src/store/:

src/store/
├── index.js            ← createStore: registers the modules and the global options
└── modules/
    ├── rooms.js        ← export default { namespaced: true, state, getters, mutations, actions }
    ├── bookings.js
    └── session.js
  • index.js stays short: it imports the modules and creates the store. It is the "table of contents" of the application's state.
  • Each module exports an object, with state as a function.
  • In large projects you will also see one folder per module (modules/bookings/index.js, getters.js, mutations.js, actions.js). It splits things further, but forces you to jump between four files to follow a feature; with modules of a reasonable size, a single file is more convenient.

  1. Case study: Colmena in three modules

9.1 Simulated authentication, in the API layer

Like the bookings, the session has a part that the server would handle: checking the email address and the password. In src/session.js it was mixed up with the state. We separate it into src/api/session.js, with the same fictitious accounts as in 04-06:

// src/api/session.js
// Simulated authentication. In a real application, the SERVER does the checking.
import { wait } from './simulation.js'

const DEMO_MEMBERS = [
  { name: 'Laura Gómez', email: '[email protected]', plan: 'flexible', role: 'member' },
  { name: 'Marta Vidal', email: '[email protected]', plan: 'business', role: 'manager' }
]
const DEMO_PASSWORD = 'colmena'

// Returns the member's details or throws an error if the credentials are not valid
export async function authenticate(email, password) {
  await wait(600)
  const member = DEMO_MEMBERS.find((m) => m.email === email.trim().toLowerCase())
  if (!member || password !== DEMO_PASSWORD) {
    throw new Error('Incorrect email or password')
  }
  return { ...member }
}

We use wait without failSometimes: having sign-in fail at random would only get in the way while practising.

9.2 src/store/modules/rooms.js

Create the src/store/modules/ folder and move the corresponding part of the previous lesson's store into each module. The prefixes disappear:

// src/store/modules/rooms.js
import { fetchRooms } from '@/api/rooms.js'

const CATALOG_MAX_AGE_MS = 5 * 60 * 1000

export default {
  namespaced: true,

  state: () => ({
    list: [],
    loadedAt: null,
    loading: false,
    error: null
  }),

  getters: {
    availableRooms: (state) => state.list.filter((room) => room.available),
    roomById: (state) => (id) => state.list.find((room) => room.id === id)
  },

  mutations: {
    startLoading(state) {
      state.loading = true
      state.error = null
    },
    setRooms(state, rooms) {
      state.list = rooms
      state.loadedAt = Date.now()
      state.loading = false
    },
    setError(state, message) {
      state.error = message
      state.loading = false
    }
  },

  actions: {
    async loadRooms({ state, commit }, { force = false } = {}) {
      const fresh = state.loadedAt !== null && Date.now() - state.loadedAt < CATALOG_MAX_AGE_MS
      if (fresh && !force) return

      commit('startLoading')
      try {
        commit('setRooms', await fetchRooms())
      } catch (error) {
        commit('setError', error.message)
      }
    }
  }
}

One detail: loadRooms receives its payload with a default value (= {}). When another module dispatches it with dispatch('rooms/loadRooms', null, { root: true }), the payload is null, and JavaScript default values only apply to undefined. Destructuring null would throw an error. That is why, from other modules, we will dispatch it with undefined (or with {}), never with null.

9.3 src/store/modules/bookings.js

// src/store/modules/bookings.js
import {
  fetchBookings,
  createBooking as apiCreateBooking,
  cancelBooking as apiCancelBooking
} from '@/api/bookings.js'
import { durationHours, currentMonth } from '@/utils/dates.js'

export default {
  namespaced: true,

  state: () => ({
    list: [],
    loading: false,
    error: null
  }),

  getters: {
    activeBookings: (state) => state.list.filter((booking) => booking.status !== 'cancelled'),

    // The prices are in another module: rootGetters
    monthlyBookingsTotal(state, getters, rootState, rootGetters) {
      const month = currentMonth()
      return getters.activeBookings
        .filter((booking) => booking.date.startsWith(month))
        .reduce((total, booking) => {
          const room = rootGetters['rooms/roomById'](booking.roomId)
          if (!room) return total
          return total + room.hourlyPrice * durationHours(booking.startTime, booking.endTime)
        }, 0)
    }
  },

  mutations: {
    startLoading(state) {
      state.loading = true
      state.error = null
    },
    setBookings(state, bookings) {
      state.list = bookings
      state.loading = false
    },
    setError(state, message) {
      state.error = message
      state.loading = false
    },
    addBooking(state, booking) {
      state.list.push(booking)
    },
    updateBooking(state, booking) {
      const index = state.list.findIndex((b) => b.id === booking.id)
      if (index !== -1) state.list[index] = booking
    },
    // On signing out, no data from the previous member must remain
    clear(state) {
      state.list = []
      state.error = null
    }
  },

  actions: {
    async loadBookings({ commit, dispatch }) {
      await dispatch('rooms/loadRooms', undefined, { root: true }) // another module's action
      commit('startLoading')
      try {
        commit('setBookings', await fetchBookings())
      } catch (error) {
        commit('setError', error.message)
      }
    },

    async createBooking({ commit }, data) {
      const created = await apiCreateBooking(data)
      commit('addBooking', created)
      return created
    },

    async cancelBooking({ commit }, id) {
      const updated = await apiCancelBooking(id)
      commit('updateBooking', updated)
      return updated
    }
  }
}
  • monthlyBookingsTotal is the natural example of rootGetters: the amount depends on two modules.
  • loadBookings dispatches an action from rooms with { root: true } and an undefined payload (section 9.2).
  • clear is new: signing out will use it.

9.4 src/store/modules/session.js

The session module replaces src/session.js. It keeps the same model (name, email, plan, role) and the persistence in sessionStorage, but active becomes a getter: it is not data, but a conclusion derived from the data (there is a session if there is an email address).

// src/store/modules/session.js
import { authenticate } from '@/api/session.js'

const STORAGE_KEY = 'colmena-session'

function createEmptySession() {
  return { name: '', email: '', plan: 'flexible', role: 'member' }
}

// If the tab already had a session (on reload), it is recovered
function readSavedSession() {
  try {
    const saved = JSON.parse(sessionStorage.getItem(STORAGE_KEY))
    return saved ? { ...createEmptySession(), ...saved } : createEmptySession()
  } catch {
    return createEmptySession()
  }
}

export default {
  namespaced: true,

  state: () => readSavedSession(),

  getters: {
    active: (state) => state.email !== '',
    isManager: (state, getters) => getters.active && state.role === 'manager'
  },

  mutations: {
    // Object.assign keeps the SAME state object (it does not replace it)
    setMember(state, { name, email, plan, role }) {
      Object.assign(state, { name, email, plan, role })
    },
    reset(state) {
      Object.assign(state, createEmptySession())
    }
  },

  actions: {
    async signIn({ commit, dispatch }, { email, password }) {
      const member = await authenticate(email, password) // if it fails, the error reaches the dispatcher
      commit('setMember', member)
      sessionStorage.setItem(STORAGE_KEY, JSON.stringify(member))
      dispatch('bookings/loadBookings', undefined, { root: true }) // no await: let it load in the background
    },

    signOut({ commit }) {
      commit('reset')
      sessionStorage.removeItem(STORAGE_KEY)
      commit('bookings/clear', null, { root: true })
    }
  }
}

Let's analyse the decisions:

  • state: () => readSavedSession(): the initial state is read from storage when the store is created. Because state is a function, every store created (for example, in a test) reads its own.
  • Writing to sessionStorage goes in the actions, not in the mutations. Writing to storage is a side effect; mutations should confine themselves to changing the state. In 05-05 we will move persistence out of the module with a plugin.
  • signIn receives an object { email, password }: the payload is a single argument.
  • dispatch('bookings/loadBookings', ...) without await: on signing in, the bookings start loading, but LoginView does not have to wait for them before navigating.
  • signOut commits bookings/clear at the root: this is the case from section 5. We accept it here because clearing is a simple operation with no logic; if it were more complex, we would create an action in bookings.
  • Object.assign in the mutations modifies the existing state object instead of replacing it. This matters for the App.vue bridge in section 9.7, which keeps references to its properties.

9.5 src/store/index.js

The main file is reduced to its role as an index:

// src/store/index.js
// Colmena Bookings store (Vuex 4)
import { createStore } from 'vuex'
import rooms from './modules/rooms.js'
import bookings from './modules/bookings.js'
import session from './modules/session.js'

const store = createStore({
  strict: import.meta.env.DEV,
  modules: { rooms, bookings, session }
})

export default store

9.6 The router reads the session from the store

The guards from 04-06 read session imported from src/session.js. Now they read it from the store, which is also an importable JavaScript module. In src/router/index.js:

// src/router/index.js: replaces import { session } from '@/session.js'
import store from '@/store'
// The login route: its per-route guard
beforeEnter: () => (store.getters['session/active'] ? { name: 'dashboard' } : true)
// The global guard
router.beforeEach((to) => {
  const requiresSession = to.matched.some((record) => record.meta.requiresSession)
  if (requiresSession && !store.getters['session/active']) {
    return { name: 'login', query: { redirect: to.fullPath } }
  }
  const requiredRole = to.meta.role
  if (requiredRole && store.state.session.role !== requiredRole) {
    return { name: 'dashboard-profile' }
  }
})
  • Importing the store into the router is fine because the store does not import the router: there is no circular dependency. If an action ever needed to navigate, the caller that dispatches it (a component) would do so, not the store.
  • The state and the getters are read every time the guard runs, so they are always up to date.

9.7 LoginView and the App.vue bridges

LoginView imported signIn from src/session.js. Now it dispatches the module's action (using useStore in components is covered in depth in 05-04):

// LoginView.vue: replaces import { signIn } from '@/session.js'
import { useStore } from 'vuex'

const store = useStore()

// In submit(), replace the call to signIn:
await store.dispatch('session/signIn', { email: email.value, password: password.value })

The rest of submit() (the try/catch that shows the error, submitting and the router.replace) does not change: the action throws the same error as the old function.

In App.vue, both provide calls now read from the store. Replace the session block and update the bookings one:

// App.vue
import { computed, provide, reactive, readonly, toRefs } from 'vue'
import { useStore } from 'vuex'
import { SESSION_KEY, BOOKINGS_KEY } from './keys.js'

const store = useStore()

// --- Session: TEMPORARY BRIDGE to the session module ---
// A reactive object with the state's fields and the "active" getter, so that components
// keep reading session.name, session.role or session.active unchanged
const session = readonly(
  reactive({
    ...toRefs(store.state.session),
    active: computed(() => store.getters['session/active'])
  })
)
provide(SESSION_KEY, { session, signOut: () => store.dispatch('session/signOut') })

// --- Bookings: TEMPORARY BRIDGE to the bookings module ---
provide(BOOKINGS_KEY, {
  bookings: computed(() => store.state.bookings.list),
  recordBooking: (booking) => store.dispatch('bookings/createBooking', booking)
})

store.dispatch('bookings/loadBookings') // TEMPORARY (05-04)

The session bridge deserves an explanation:

  • toRefs(store.state.session) creates a ref linked to each property of the module's state: reading name.value reads store.state.session.name. That is why it was important for the mutations to use Object.assign on the same object: if a mutation replaced the state object, these refs would still point to the old one.
  • reactive({ ...refs, active: computed }) automatically unwraps the refs it contains: session.name returns the string, not a ref. That way AppHeader, DashboardView, DashboardProfileView and BookingForm, which read session.name or session.active, do not change.
  • readonly, as before: components cannot modify the session.

It is clever, but it is scaffolding. In the next lesson the components will read the store directly and both provide calls will disappear.

Finally, delete src/session.js. If any file still imports it, Vite will show the error immediately.

9.8 Try it

  1. Open the application with DevTools. In the Vuex inspector, the state now has three branches: rooms, bookings and session. The getters appear with their prefix (rooms/availableRooms, session/active...).
  2. Click "My dashboard" without a session: the router takes you to the login page, as before, but now by checking session/active.
  3. Sign in as Marta Vidal. In the timeline you will see session/signIn, the session/setMember mutation, and then bookings/loadBookings dispatched from the session module. Open "Invoices": the guard reads store.state.session.role.
  4. Reload the page: the session is kept (the module's initial state is read from sessionStorage).
  5. Sign out: you will see session/signOut, session/reset and bookings/clear. In the inspector, bookings.list is empty.
  6. Check that there are no references to src/session.js left in the project (a global search for session.js in the editor).

Common Mistakes and Tips

  • Forgetting namespaced: true. Mutations with the same name in several modules all run with a single commit, and getters with the same name clash. Enable it in every module.
  • Using the prefixed name inside the module itself (commit('bookings/addBooking') inside bookings). Inside, the names are local; with a prefix, it would look for bookings/bookings/addBooking.
  • Forgetting { root: true } when dispatching another module's action: Vuex looks for the action inside the current module and warns that it does not exist.
  • Dispatching with null an action that destructures its payload with a default value. The default value only applies to undefined.
  • Reading store.getters.bookings/activeBookings with a dot. With a prefix, use square brackets: store.getters['bookings/activeBookings'].
  • Replacing a module's state object (state = {...} does not work inside a mutation; reassigning a branch from outside breaks references). Modify its properties.
  • Creating cross-dependencies between every module. If rooms reads from bookings and bookings from rooms, perhaps the split is not the right one.
  • Tip: treat each module's actions as its public interface. From outside, dispatch actions; commit another module's mutations only in simple, justified cases.
  • Tip: register dynamically only the modules for features that are genuinely optional and heavy. For small modules used by the whole application, static registration is simpler.

Exercises

Exercise 1. Given this store, write how each operation would be done from a component and from an action in the bookings module: (a) read the loading state of rooms; (b) read the availableRooms getter; (c) dispatch loadRooms forcing a reload; (d) commit the addBooking mutation of bookings.

createStore({ modules: { rooms: { namespaced: true, /* ... */ }, bookings: { namespaced: true, /* ... */ } } })

Exercise 2. Add to the bookings module a myBookings getter that returns the active bookings whose member matches the name in the signed-in session. If the session belongs to a manager, it must return all the active bookings. Which of the getter's arguments do you need?

Exercise 3. Create a billing module (in src/store/modules/billing.js) with the invoices state (the three fictitious invoices currently in DashboardInvoicesView), an outstandingAmount getter and a markPaid(number) mutation. Register it dynamically from DashboardInvoicesView and make the view use it. Check in DevTools that the module does not appear in the state until a manager opens the invoices.

Solutions

Solution 1.

Operation From a component From a bookings action
(a) store.state.rooms.loading rootState.rooms.loading
(b) store.getters['rooms/availableRooms'] rootGetters['rooms/availableRooms']
(c) store.dispatch('rooms/loadRooms', { force: true }) dispatch('rooms/loadRooms', { force: true }, { root: true })
(d) store.commit('bookings/addBooking', b) commit('addBooking', b) (local, no prefix)

Solution 2.

// src/store/modules/bookings.js, in getters
myBookings(state, getters, rootState, rootGetters) {
  if (rootGetters['session/isManager']) return getters.activeBookings
  return getters.activeBookings.filter((booking) => booking.member === rootState.session.name)
}

You need all four: getters (to reuse activeBookings), rootState (the member's name) and rootGetters (session/isManager). The first argument, state, is not used, but it has to be declared to reach the following ones. Comparing by name is fragile (two members can have the same name); in a real API each booking would carry the member's identifier. We will come back to this getter in 05-05.

Solution 3.

// src/store/modules/billing.js
export default {
  namespaced: true,
  state: () => ({
    invoices: [
      { number: 'INV-2026-0141', date: '2026-10-01', client: 'Laura Gómez', description: 'Flexible plan · 12 room hours', amount: 300, paid: true },
      { number: 'INV-2026-0142', date: '2026-10-01', client: 'Estudio Alveolo S.L.', description: 'Business plan · October', amount: 1450, paid: false },
      { number: 'INV-2026-0143', date: '2026-10-02', client: 'Jaime Ortega', description: 'Fixed plan · October', amount: 220, paid: true }
    ]
  }),
  getters: {
    outstandingAmount: (state) =>
      state.invoices.filter((i) => !i.paid).reduce((total, i) => total + i.amount, 0)
  },
  mutations: {
    markPaid(state, number) {
      const invoice = state.invoices.find((i) => i.number === number)
      if (invoice) invoice.paid = true
    }
  }
}
<!-- DashboardInvoicesView.vue -->
<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'
import billingModule from '@/store/modules/billing.js'

const store = useStore()
if (!store.hasModule('billing')) {
  store.registerModule('billing', billingModule)
}

const invoices = computed(() => store.state.billing.invoices)
const outstanding = computed(() => store.getters['billing/outstandingAmount'])
const euroFormatter = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR' })

function markPaid(number) {
  store.commit('billing/markPaid', number)
}
</script>

In the template, the table does not change; in the status column, add a @click="markPaid(invoice.number)" button for the pending ones. The hasModule check avoids registering it again (and resetting its state) every time the manager comes back to the screen. We do not remove it on leaving, so that the changes are kept for the rest of the session. In the Network tab, check that the module's code arrives in the same file as the view.

Conclusion

Modules split the store into branches with their own state, getters, mutations and actions, while it remains a single store. With namespaced: true, everything in the module sits under its prefix ('bookings/createBooking', store.getters['rooms/roomById']) while, inside, the names remain local. Getters and actions access other modules with rootState and rootGetters, and actions dispatch or commit outside their module with { root: true }. Modules can be nested and registered dynamically with registerModule for features that are loaded on demand. In Colmena, the store is organised in src/store/modules/ with the rooms, bookings and session modules; the simulated authentication lives in src/api/session.js; src/session.js has gone, and the router checks session/active.

There is, however, some conspicuous scaffolding left: the components still receive the session and the bookings through inject, via increasingly clever bridges in App.vue, and the catalogue views still request the rooms from the API on their own. In the next lesson, Using Vuex in Components, we will connect each view directly to the store, with the Composition API and with the Options API helpers, and remove the provide calls from App.vue.

New edition · October 2026

Vue.js Course

Module 1: Introduction to Vue.js

Module 2: Vue.js Basics

Module 3: Vue.js Components

Module 4: Vue Router

Module 5: State Management with Vuex and Pinia

Module 6: Vue.js Directives

Module 7: Vue.js Plugins

Module 8: Testing in Vue.js

Module 9: Advanced Vue.js Concepts

Module 10: Building and Deploying Vue.js Applications

Module 11: Real-World Vue.js Projects

© Copyright 2026. All rights reserved