By the end of the Vue Router module, Colmena Bookings had several screens, but the state they share was spread across temporary solutions: a module with reactive for the session, a provide from App.vue for the bookings, and repeated catalogue requests in every view. In this module you will replace all of that with a centralised state container (a store). We will start with Vuex, the library through which the Vue ecosystem popularised this pattern. Today it is in maintenance mode and Pinia is recommended for new projects, but it is still present in a huge number of production applications, and as a professional you will have to maintain and migrate them. In this lesson you will see what problem a store solves, which pattern Vuex is based on, what its parts are, when it is not worth using, and how to install it. By the end, Colmena will have its first src/store/index.js and you will see every change to the bookings in the Vue DevTools timeline.
Contents
- The problem of shared state
- A pattern for managing state: Flux and one-way data flow
- A single source of truth
- The parts of Vuex
- Vuex 4 for Vue 3: where things stand
- When you do not need a store
- Installation and your first store
- Debugging with Vue DevTools
- Case study: Colmena's first store
- The problem of shared state
Until now, every time several components have needed the same piece of data we have looked for a different solution. Let's review the state of Colmena at the end of Navigation Guards:
| Shared data | Where it lives today | How it reaches whoever uses it | Problems |
|---|---|---|---|
| Member's session | src/session.js (a module with reactive) |
Imported by the router and provided again by App.vue with provide(SESSION_KEY) |
Two paths for the same data; nobody knows who changed it or when |
| Bookings created | A ref in App.vue |
provide(BOOKINGS_KEY) |
Depends on App being mounted; lost on reload; never sent to the API |
| Room catalogue | A local ref in each view |
Each view calls fetchRooms() |
HomeView, RoomsView and RoomDetailView request the same thing over and over again |
None of these solutions is wrong on its own. In Component Communication we studied provide/inject and shared state in a module, and we saw their limits. The problem appears when they pile up:
- Each piece of data follows its own rules. To read the session you inject it; in the router you import it; the catalogue is requested; the bookings are injected but modified through a function of their own. Anyone new to the project has to learn one style per piece of data.
- Changes are invisible. If a booking appears twice, there is no way of knowing which component called
recordBooking, with what data, or in what order relative to other changes. - There is no place for asynchronous logic. When the bookings have to be sent to the API, who makes the request, who manages the loading state, who handles the error? Today each component would do it in its own way.
- It does not scale. Every new screen that needs to know that a room has just filled up adds another implicit dependency.
A store solves this with a simple idea: take the shared state out of the components and put it in a central object, with explicit rules about how it is read and how it is modified.
- A pattern for managing state: Flux and one-way data flow
Vuex is inspired by Flux, the architecture Facebook proposed in 2014 for its user interfaces, and by Redux, its best-known implementation. The central idea is that data flows in one direction only:
flowchart LR
C["Component"] -->|"dispatch('createBooking', data)"| A["Action<br/>(can be asynchronous:<br/>calls the API)"]
A -->|"commit('addBooking', booking)"| M["Mutation<br/>(synchronous: changes the state)"]
M --> E["State"]
E -->|"reactivity: render"| C
A <-.->|"request / response"| API["Server API"]
Let's go through the cycle step by step with a Colmena example:
- The component does not change the state directly. When the user submits the form, the view dispatches (
dispatch) an action: "I want to create this booking". - The action does the work, which may be asynchronous: calling the API, waiting for the response, deciding what to do if it fails.
- The action commits (
commit) a mutation with the result: "add this booking to the state". - The mutation is the only thing that modifies the state, synchronously and simply.
- The state is reactive: every component that reads it re-renders.
Why so much ceremony for something a push would solve in one line? Because every state change goes through a known point (a mutation with a name and data) and in a known order. That makes it possible to record every change, replay it, undo it in the debugging tools and reason about the application without having to read every component. The ceremony is the price of traceability.
| Without a pattern | With one-way data flow |
|---|---|
| Any component modifies the data | Only mutations modify the state |
| Changes happen in any order and anywhere | Every change is an event with a name and data |
| Asynchronous logic lives in the components | It lives in the actions, reusable from any view |
| Debugging means hunting for whoever touched the data | The timeline shows every change in order |
- A single source of truth
The second principle is the single source of truth: each piece of shared data exists in one place only, the store, and everything else is a read from that place.
flowchart TD
S["Store<br/>(shared state)"]
S --> I["HomeView<br/>reads: available rooms"]
S --> SA["RoomsView<br/>reads: catalogue"]
S --> P["DashboardBookingsView<br/>reads: bookings"]
S --> CA["AppHeader<br/>reads: session"]
S --> R["router.beforeEach<br/>reads: session"]
Compare this with the current situation, in which the catalogue exists in three copies (one per view) that may not match. With a store:
- There are no copies to keep in sync. If a room goes into maintenance, every screen sees it at the same time.
- The state can be inspected in one go. Vue DevTools shows the whole object; you could serialise it to JSON and you would have a "snapshot" of the application.
- Access is uniform. A component, the router or any JavaScript module reads the state in the same way.
That does not mean all state should go into the store. The text the user is typing in a field, whether a drop-down is open or the current page of a table are local state of the component, and they should stay that way. What goes into the store is what several distant parts of the application share, or what must survive a component being unmounted. We will come back to this in section 6.
- The parts of Vuex
A Vuex store is made up of five parts. You will see them one by one in the next few lessons; this table is the map:
| Part | Responsibility | Equivalent in a component | Covered in |
|---|---|---|---|
state |
The shared, reactive data | ref/reactive |
05-02 |
getters |
Values derived from the state, cached | computed |
05-02 |
mutations |
The only functions that modify the state; synchronous | Assigning to a ref |
05-02 |
actions |
Business and asynchronous logic; they commit mutations | An async function that calls the API |
05-02 |
modules |
Split the store into parts with their own state, getters, mutations and actions | Organising code by feature | 05-03 |
And two verbs worth memorising right now:
commit('mutationName', payload): runs a mutation. Synchronous.dispatch('actionName', payload): runs an action. Always returns a promise.
How they are used from components (useStore, the mapState and mapActions helpers...) is the subject of Using Vuex in Components. In this lesson we will use only the bare essentials.
- Vuex 4 for Vue 3: where things stand
There are two major versions of Vuex in use:
| Version | For | Status |
|---|---|---|
| Vuex 3 | Vue 2 | Unsupported, like Vue 2 (end of life on 31/12/2023) |
| Vuex 4 | Vue 3 | Maintenance: fixes critical bugs, adds no new features |
Vuex 4 is the adaptation of Vuex to Vue 3, with an API almost identical to that of Vuex 3: the main change is that the store is created with createStore (instead of new Vuex.Store) and that it can be used with the Composition API through useStore(). This made it easier for thousands of applications to migrate from Vue 2 to Vue 3 without rewriting their state management.
However, the official Vue documentation is clear: for new projects, the recommendation is Pinia. Pinia began as an experiment for the next version of Vuex ("Vuex 5") and ended up becoming the official library. There is no Vuex 5, and there never will be. We will study it in 05-06.
So why start with Vuex?
- Because you will come across it. Almost every Vue application built between 2016 and 2022 uses Vuex, and many are still in production. Maintaining, extending or migrating that code is everyday work.
- Because the concepts carry over. State, getters and actions exist in exactly the same way in Pinia. Mutations disappear, but understanding why they existed will help you appreciate what Pinia simplifies.
- Because migrating requires knowing both sides. In 05-07 you will migrate Colmena from Vuex to Pinia incrementally, as you would in a real project.
That is why, in this module, we will treat Vuex for what it is: a legacy technology, but a very much alive one, which is worth mastering so that you can leave it behind safely.
- When you do not need a store
A store has a cost: more files, more indirection and a learning curve for the team. Before adding one, ask yourself whether your case needs it.
| Situation | Store? | Alternative |
|---|---|---|
| A piece of data is only used by one component | No | Local state (ref) |
| A direct parent and child share data | No | Props and events, v-model |
| Two siblings coordinate | Usually not | Lift the state up to the common parent |
| Context data that rarely changes (configuration, theme) | No | provide/inject or app.provide |
| The state can be represented in the URL (filters, page, tab) | No | The route's query (like the catalogue filters in 04-05) |
| A small application with a couple of global values | Perhaps not | A module with reactive and functions, or a composable |
| Several screens read and modify the same data, with asynchronous logic, and it needs debugging | Yes | — |
Note that in Colmena we will not move the catalogue filters into the store: they already have an excellent source of truth, the URL. Nor the centre's configuration (CONFIG_KEY), which is immutable context data well served by app.provide. What will go into the store is the session, the bookings and the catalogue: data that several screens share, that comes from the API and that changes.
- Installation and your first store
7.1 Installing Vuex 4
In the project folder:
@4matters: it pins the major version. Without it, npm would install the latest version published under thelatesttag, which is 4.x, but in legacy projects you will often seevuex@3, and the two must not be mixed: Vuex 3 only works with Vue 2.- Check that
package.jsonlists something like"vuex": "^4.1.0"underdependencies.
7.2 Creating the store with createStore
The minimal store has state and, so that it can be modified, at least one mutation:
// Generic example
import { createStore } from 'vuex'
const store = createStore({
// The initial state: a FUNCTION that returns an object
state() {
return {
counter: 0
}
},
// The only functions that can modify the state
mutations: {
increment(state, amount) {
state.counter += amount
}
}
})
export default storecreateStore(options)creates the store. There should be only one per application.state()is a function, just likedata()in the Options API. We will see why in 05-02; for now, always write it this way.- Each mutation receives the
stateas its first argument and, optionally, a second argument with the data for the change (the payload).
7.3 Installing it in the application: app.use(store)
Like the router, the store is a Vue plugin: it is installed with app.use before mounting.
// main.js (generic)
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
createApp(App).use(store).mount('#app')app.use(store) does two things:
- It makes the store available to every component: with
useStore()in<script setup>and asthis.$store(or$storein the template) in the Options API. - It registers the integration with Vue DevTools.
7.4 Reading and modifying
A first taste, which we will expand on in the next few lessons:
<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
// Reading: wrapped in computed so that it is reactive and read-only
const counter = computed(() => store.state.counter)
// Modifying: by committing a mutation
function addOne() {
store.commit('increment', 1)
}
</script>
<template>
<button @click="addOne">Clicked {{ counter }} times</button>
</template>useStore()returns the store installed withapp.use. It must be called at the top level of<script setup>, likeuseRouter().store.state.counteris reactive:store.stateis areactiveobject. We wrap it incomputedto have a convenient reference in the template and to make it clear that it is for reading. The details of this pattern are in 05-04.store.commit('increment', 1): the mutation's name as a string, plus the payload.
Could a component write store.state.counter++? Technically yes, and Vue would render it. But it would bypass the pattern: the change would not be recorded and nobody would know who made it. In 05-02 we will enable strict mode, which turns that shortcut into an error during development.
- Debugging with Vue DevTools
The great practical advantage of a store is observability. Vuex 4 registers itself in Vue DevTools through its plugin API. In the current version of the extension (Vue DevTools 7), Vuex appears as a plugin with its own panel; the exact location of each tab varies between versions of the extension, but you will find two tools:
| Tool | What it shows | What it is for |
|---|---|---|
| Vuex inspector | The tree of the state and the getters, with their current values | Checking what data the store holds right now; editing a value to try something out |
| Timeline, "Vuex Mutations" and "Vuex Actions" layers | Every mutation committed and every action dispatched, in order, with its payload and the time | Knowing what changed, when and with what data |
A typical debugging workflow:
- Open the browser's developer tools and the Vue tab.
- Start recording the timeline if it is not already recording.
- Reproduce the problem in the application (for example, create a booking).
- In the timeline, select the mutation event: you will see its type (
addBooking), its payload (the booking) and the resulting state.
If you use the Vite plugin vite-plugin-vue-devtools that we saw in 01-02, the same tools are available inside the page itself. If you cannot see the Vuex panel, check that you are in development mode (npm run dev) and that the store was installed with app.use(store) before mount.
Compare this with the situation in 04-06: with provide and a ref in App.vue, DevTools showed the current value of bookings, but not who changed it or when.
- Case study: Colmena's first store
We will start with the simplest part: the bookings, which currently live in a ref in App.vue. We will move the state into the store and make the existing provide read it from there. That way no component has to change yet (we will do that in 05-04), and from the very first moment every booking will be recorded in the timeline.
9.1 Installing Vuex
9.2 Creating src/store/index.js
Create the src/store/ folder (singular: that is the convention in projects that use Vuex) and, inside it, index.js:
// src/store/index.js
// Colmena Bookings store (Vuex 4)
import { createStore } from 'vuex'
const store = createStore({
state() {
return {
bookings: [] // the bookings created in this session
}
},
mutations: {
// Adds a booking already built (by BookingForm) to the list
addBooking(state, booking) {
state.bookings.push(booking)
}
}
})
export default storebookings: []is the same data as theref([])inApp.vue, now in the store.addBookingreplacesrecordBooking: it receives the booking as its payload and adds it. No moreconsole.logto keep track of the bookings: DevTools will do that.
9.3 Installing it in main.js
// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store' // NEW
import { CONFIG_KEY } from './keys.js'
import './assets/main.css'
const app = createApp(App)
app.config.errorHandler = (error, instance, info) => {
// ... unchanged ...
}
app.provide(CONFIG_KEY, { centreName: 'Coworking Colmena', openingHour: 8, closingHour: 20 })
app.use(store) // NEW: before the router, so that the guards find it ready
app.use(router)
app.mount('#app')The order of app.use(store) and app.use(router) is not critical right now, but installing the store first is a good habit: in 05-03 the router's guards will read the session from the store, and app.use(router) triggers the initial navigation.
9.4 App.vue provides what is in the store
In the <script setup> of App.vue, replace the bookings block (the ref, recordBooking and its provide):
// App.vue
import { computed, provide } from 'vue' // ref and readonly are no longer needed for the bookings
import { useStore } from 'vuex'
const store = useStore()
// --- Bookings: they now live in the store ---
// TEMPORARY BRIDGE: components still use inject(BOOKINGS_KEY); in 05-04 they will read from the store
provide(BOOKINGS_KEY, {
bookings: computed(() => store.state.bookings),
recordBooking: (booking) => store.commit('addBooking', booking)
})The session block (provide(SESSION_KEY, { session, signOut }) with src/session.js) does not change yet.
Let's analyse this bridge:
computed(() => store.state.bookings)is a read-onlyrefwhose value is the store's array.DashboardBookingsViewusesbookings.value.toSorted(...)andBookingViewshowsbookings.lengthin the template: both keep working just as they did with the previousreadonly(ref).recordBookingkeeps its name and signature, but now it commits a mutation.BookingViewstill calls it in the same way.- It is temporary: a component that injects
bookingscould, in theory, dobookings.value.push(...)on the store's array without going through the mutation. The previousreadonlyprevented this; the strict mode in 05-02 will detect it, and in 05-04 theprovidewill disappear.
flowchart LR
VR["BookingView"] -->|"recordBooking(booking)<br/>(inject)"| P["Bridge in App.vue"]
P -->|"commit('addBooking')"| S["Store: state.bookings"]
S -->|"computed"| P2["inject(BOOKINGS_KEY).bookings"]
P2 --> VP["DashboardBookingsView"]
9.5 Try it
- Start the app with
npm run dev, sign in and create a booking in the Néctar Room. You land on "My bookings" with the booking highlighted, as before. - Open Vue DevTools and look for the Vuex panel: in the state you will see
bookingswith one element. Expand it: it is the booking with all its fields. - Go to the timeline, Vuex mutations layer. Create another booking: an
addBookingevent appears. Select it and examine its payload. - In the component inspector, select
App: it no longer has abookingsrefof its own. The data has left the component. - Reload the page: the bookings disappear. It is still in-memory state; in the next lesson we will send them to a simulated API that does keep them.
Common Mistakes and Tips
- Installing
vuexwithout a version in a legacy Vue 2 project, orvuex@3in a Vue 3 one. Vuex 3 ↔ Vue 2; Vuex 4 ↔ Vue 3. They do not mix. - Calling
app.use(store)aftermount. The components will not find the store (useStore()will returnundefined) and DevTools will not register it. - Writing
stateas an object instead of a function. It works in an application with a single store, but it causes problems when the definition is reused (tests, reusable modules). Get used tostate() { return { ... } }. - Modifying
store.statedirectly from a component. It works, but it breaks traceability, which is the store's whole reason for being. Always use mutations (and actions, as you will see). - Putting everything in the store. The state of a half-filled form, whether a menu is open or the active tab of a panel are local state. A store full of interface details is as hard to maintain as the hundreds-of-lines
App.vuefrom module 2. - Tip: before moving a piece of data into the store, ask yourself two questions: do components that are far apart from each other need it? Must it survive the component that uses it being unmounted? If the answer to both is no, leave it where it is.
- Tip: keep the DevTools timeline open while you develop with a store. Watching each mutation go by is the quickest way to understand (and to spot mistakes in) the data flow.
Exercises
Exercise 1. Classify each piece of Colmena data according to where it should live (local state, URL, provide/app.provide or store) and justify your answer in one sentence:
a) The text the user types into the notes of the booking form. b) The catalogue filters (floor, capacity, equipment). c) The centre's opening hours. d) The member's list of bookings. e) Whether the reception clock is visible. f) The details of the member who has signed in.
Exercise 2. Add a clearBookings mutation to Colmena's store that empties the list, and a temporary "Clear (testing)" button in DashboardBookingsView that commits it. As the view still uses inject, add the function to the bridge in App.vue. Check in the timeline that the event appears. What would be the problem with implementing the clearing as bookings.value = [] in the view?
Exercise 3. A colleague proposes not using mutations: "it's shorter to write store.state.bookings.push(booking) from the view, and DevTools still shows the state". Write a reasoned reply with at least three arguments.
Solutions
Solution 1.
| Data | Place | Why |
|---|---|---|
| a) Form notes | Local state of BookingForm |
Only the form uses it and it must not outlive the form (in fact, it is reset) |
| b) Catalogue filters | URL (query) | They must be shareable, bookmarkable and survive a reload; we already solved this in 04-05 |
| c) Centre opening hours | app.provide |
Immutable context data needed by several components |
| d) Bookings | Store | Several screens read and modify them, and they will come from the API |
| e) Clock visible | Local state of AppHeader |
It is a presentation detail of a single component |
| f) Signed-in member | Store | The header, the dashboard, the form and the router (outside the components) all need it |
Solution 2.
// App.vue, in the bridge
provide(BOOKINGS_KEY, {
bookings: computed(() => store.state.bookings),
recordBooking: (booking) => store.commit('addBooking', booking),
clearBookings: () => store.commit('clearBookings')
})<!-- DashboardBookingsView.vue -->
<script setup>
// ...
const { bookings, clearBookings } = inject(BOOKINGS_KEY)
</script>
<template>
<!-- ... -->
<BaseButton variant="danger" @click="clearBookings">Clear (testing)</BaseButton>
</template>Assigning state.bookings = [] inside the mutation is correct: state is reactive and reassigning a property is detected. In the view, bookings.value = [] would not work: bookings is a read-only computed (Vue would log a warning in the console and nothing would change). And even if it did work, the change would not be recorded. Remember to remove the button when you have finished.
Solution 3. Possible arguments:
- Traceability: a mutation appears in the timeline with its name and payload; a direct
pushdoes not. When something goes wrong, we will not know who did it. - A single place for each change: if tomorrow the booking has to be validated or the list kept sorted, you change the mutation; with
pushcalls scattered around, you would have to hunt them all down. - Strict mode forbids it: in development, Vuex will throw an error when it detects changes outside mutations (05-02).
- Team consistency: if it is allowed in one place, it will end up being done everywhere, and the store will become just another global object, with the problems of state in a module from 03-07.
Conclusion
A store centralises the state shared by distant parts of the application and defines clear rules for reading and modifying it. Vuex applies the pattern inspired by Flux: components dispatch actions, actions do the work (including asynchronous work) and commit mutations, mutations modify the state, and reactivity re-renders the components. That one-way data flow and the single source of truth make every change traceable in the Vue DevTools timeline. You know the five parts of Vuex (state, getters, mutations, actions, modules), you know that Vuex 4 is the version for Vue 3 and that it is in maintenance mode (Pinia is the recommendation for new projects), and you can recognise when you do not need a store. In Colmena you have installed Vuex, created src/store/index.js with the bookings state and the addBooking mutation, and the provide in App.vue is now just a bridge to the store.
But this store is still a simple container: the bookings are still in memory, the catalogue is still requested in every view and nothing knows about loading or errors. In the next lesson, State, Getters, Mutations and Actions, we will study each part in depth, create the simulated bookings API and turn the store into the place where Colmena's data logic lives.
Vue.js Course
Module 1: Introduction to Vue.js
- What Is Vue.js?
- Setting Up the Development Environment
- Creating Your First Vue Application
- Understanding the Vue Instance: Application, Components and Lifecycle
- Options API and Composition API: Two Ways to Write Components
Module 2: Vue.js Basics
- Template Syntax
- Reactivity: ref and reactive
- Data Binding
- Event Handling
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Forms with v-model
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- v-model on Your Own Components
- Slots
- Template Refs and Fallthrough Attributes
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
- Introduction to Vue Router
- Setting Up Vue Router
- Dynamic Routes
- Nested Routes
- Programmatic Navigation and Query Parameters
- Navigation Guards
Module 5: State Management with Vuex and Pinia
- Introduction to Vuex
- State, Getters, Mutations and Actions
- Vuex Modules
- Using Vuex in Components
- Advanced Vuex Patterns
- Pinia: The Recommended State Management for Vue 3
- Migrating from Vuex to Pinia
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
- Unit Testing with Vue Test Utils and Vitest
- Mocking Dependencies
- Testing Composables and Stores
- End-to-End Testing with Cypress
Module 9: Advanced Vue.js Concepts
- The Vue 3 Composition API in Depth: Composables and Logic Reuse
- Vue with TypeScript
- Render Functions and JSX
- Transitions and Animations
- Teleport, Suspense and Error Handling
- Server-Side Rendering (SSR) with Nuxt
- Performance Optimization
