Colmena's store is now organised into three modules, but the components hardly know it exists: they receive the session and the bookings through inject, via two bridges in App.vue, and the catalogue views still request the rooms from the API on their own. In this lesson you will learn to connect components directly to the store. First with the Composition API (useStore(), computed, dispatch and commit in <script setup>), which is how we will write Colmena; then with the Options API (this.$store and the mapState, mapGetters, mapMutations and mapActions helpers), which is how most of the Vuex code you will find in existing projects is written. You will also see how to use v-model on store state without bypassing mutations, why you should not destructure the state, and which components should know about the store and which should not. By the end, every Colmena view will read from the store and App.vue will once again be a simple frame.
Contents
useStore()in<script setup>- Reading state and getters with
computed - Dispatching actions and committing mutations
- Why not to destructure the state
v-modelon store state- Options API:
this.$storeand themap*helpers - Composition API and Options API equivalents
- Good practice: connected views and presentational components
- Case study: connecting Colmena to the store
useStore() in <script setup>
useStore() in <script setup>useStore() returns the store installed with app.use(store):
- Call it at the top level of
<script setup>, while the component is being created, likeuseRoute()orinject(). Under the hood,useStoreis aninject: it looks for the store thatapp.useprovided to the whole application. - Outside components (in the router, in a JavaScript module) you cannot use
useStore(): there, you import the store directly, as we did in the guards in 05-03.
So why not import the store in components too (import store from '@/store')? It would work in a browser application, but useStore() has advantages: the component receives the store of the application it is mounted in, which makes it possible to mount it in a test with a test store (08-03) or on a server with one store per request. Rule of thumb: in components, useStore(); outside them, import.
- Reading state and getters with
computed
computedState and getters are read through the store and wrapped in computed:
import { computed } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
// A module's state
const rooms = computed(() => store.state.rooms.list)
const loading = computed(() => store.state.rooms.loading)
// Getter
const availableRooms = computed(() => store.getters['rooms/availableRooms'])
// Getter with an argument: the computed property also depends on the prop
const { id } = defineProps({ id: String })
const room = computed(() => store.getters['rooms/roomById'](id))Why computed?
- Reactivity: the function is re-evaluated when what it reads changes. If a mutation replaces
state.rooms.listwith a new array, the computed property returns the new one. - Read-only: a computed property without a
setcannot be assigned to. It makes it clear that the component reads the store and does not modify it. - Convenience in the template:
rooms,loadingorroomare used like anyref(v-for="r in rooms"), without repeatingstore.state.rooms...in the markup. - A cache for getters with arguments: as we saw in 05-02,
roomById(id)does not cache its result; the computed property does, as long as neitheridnor the catalogue changes.
You can also read the store directly in the template ({{ $store.state.rooms.loading }}): $store is available in every template. That is fine for a one-off, but computed properties keep the list of the component's dependencies on the store in the script.
- Dispatching actions and committing mutations
Actions and mutations are run from the component's functions:
// Action: returns a promise
async function cancel(id) {
try {
await store.dispatch('bookings/cancelBooking', id)
} catch (error) {
message.value = error.message
}
}
// Mutation: synchronous
function chooseView(view) {
store.commit('rooms/setCatalogView', view)
}When should a component dispatch an action and when should it commit a mutation? The general rule is that components dispatch actions: that way the component does not know whether the change needs the API, a validation or several mutations, and those details can change without touching it. Committing a mutation directly is acceptable for changes that are purely local to the client, synchronous and free of logic (changing a display preference), and many teams avoid it anyway for the sake of uniformity. In Colmena, components will dispatch actions except for the catalogue view preference.
A common detail: loading the data when the view is created. It is enough to dispatch at the top level of the script:
There is no need for onMounted: the action does not touch the DOM, and starting the request before mounting gains a few milliseconds. Nor is await needed: the view shows the store's loading state in the meantime.
- Why not to destructure the state
It is tempting to write:
list and loading are now ordinary variables holding the value they had at that instant: loading is false forever, and list points to the initial array. When the setRooms mutation does state.list = rooms, the state property starts pointing to another array, but the variable still points to the old one. This is the problem we studied with reactive in 02-02.
What about toRefs?
It keeps reactivity, but the resulting refs can be written to: loading.value = true would modify the store's state outside a mutation (and strict mode would throw an error). It also ties the component to the internal shape of the state.
| Form | Reactive? | Can it be written to by mistake? | Recommendation |
|---|---|---|---|
const { x } = store.state.m |
No | — | Never |
const { x } = toRefs(store.state.m) |
Yes | Yes (bypasses mutations) | Avoid |
const x = computed(() => store.state.m.x) |
Yes | No | Yes |
The same goes for getters: const { availableRooms } = store.getters does not work as you would expect. One computed property per value.
v-model on store state
v-model on store statev-model writes to its variable. If the variable is a computed property that reads the store, v-model cannot write to it (Vue warns that it is read-only). And writing directly to store.state would bypass the mutations. The solution is a writable computed (02-05) whose set commits a mutation (or dispatches an action):
const catalogView = computed({
get: () => store.state.rooms.catalogView,
set: (view) => store.commit('rooms/setCatalogView', view)
})<select v-model="catalogView">
<option value="grid">Grid</option>
<option value="table">Table</option>
<option value="map">Map</option>
</select>flowchart LR
U["The user chooses 'Table'"] --> SET["set('table')"]
SET -->|"commit('rooms/setCatalogView')"| M["Mutation"]
M --> E["state.rooms.catalogView = 'table'"]
E --> GET["get() → 'table'"]
GET --> V["The select shows 'Table'"]
The cycle is the same as with the URL filters in 04-05, with the store instead of the URL: the value is not stored in the component; the set sends it to the store and the get reads it back.
The alternative without a computed property is to split v-model into :value and @change:
It is valid, but the writable computed is more readable and works in the same way with v-model on your own components.
Be careful with objects: if you do v-model="form.name" on an object that comes from the store (form = computed(() => store.state.x.form)), the computed's set does not come into play: v-model modifies the property of the store's object directly, outside any mutation. For forms that edit store data, the usual pattern is to work on a local copy and dispatch an action on saving, as BookingForm does.
- Options API:
this.$store and the map* helpers
this.$store and the map* helpersMuch of the existing Vuex code is written with the Options API. There, the store is in this.$store, and Vuex offers four helpers that generate computed properties and methods so you do not have to keep repeating this.$store....
6.1 this.$store
export default {
computed: {
loading() {
return this.$store.state.rooms.loading
},
availableRooms() {
return this.$store.getters['rooms/availableRooms']
}
},
methods: {
reload() {
this.$store.dispatch('rooms/loadRooms', { force: true })
}
},
created() {
this.$store.dispatch('rooms/loadRooms')
}
}6.2 mapState and mapGetters
They generate computed properties. They are combined with your own using the spread operator:
import { mapState, mapGetters } from 'vuex'
export default {
computed: {
// With namespaces: first argument, the module
...mapState('rooms', ['loading', 'error']), // this.loading, this.error
...mapState('rooms', { rooms: 'list' }), // renaming: this.rooms = state.rooms.list
...mapState('session', {
greeting: (state) => `Hello, ${state.name}` // function: calculated from the module's state
}),
...mapGetters('rooms', ['availableRooms', 'roomById']), // this.availableRooms, this.roomById(id)
...mapGetters('session', { hasSession: 'active' }), // renaming a getter
// A computed property of your own, alongside the mapped ones
freeCount() {
return this.availableRooms.length
}
}
}| Form | Example | Result |
|---|---|---|
| Array of names | mapState('rooms', ['loading']) |
this.loading ← state.rooms.loading |
| Object with a string | mapState('rooms', { rooms: 'list' }) |
this.rooms ← state.rooms.list |
| Object with a function | mapState('session', { greeting: (state) => ... }) |
this.greeting ← the function's result |
| No module | mapState(['counter']) |
Root state (store without modules) |
6.3 mapMutations and mapActions
They generate methods:
import { mapMutations, mapActions } from 'vuex'
export default {
methods: {
...mapActions('bookings', ['loadBookings', 'cancelBooking']),
// this.cancelBooking(id) → this.$store.dispatch('bookings/cancelBooking', id)
...mapActions('session', { onSignOut: 'signOut' }),
// this.onSignOut() → this.$store.dispatch('session/signOut')
...mapMutations('rooms', ['setCatalogView'])
// this.setCatalogView('table') → this.$store.commit('rooms/setCatalogView', 'table')
}
}The argument passed to the method arrives as the payload, and the method returns the same as dispatch (a promise) or commit.
6.4 createNamespacedHelpers
When a component makes heavy use of the same module, repeating 'bookings' in every helper gets tiresome. createNamespacedHelpers creates versions of the helpers already bound to a module:
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapGetters, mapActions } = createNamespacedHelpers('bookings')
export default {
computed: {
...mapState(['loading', 'error']), // state.bookings.loading...
...mapGetters(['activeBookings']) // getters['bookings/activeBookings']
},
methods: {
...mapActions(['cancelBooking']) // dispatch('bookings/cancelBooking')
}
}The trade-off is that those helpers only work for that module; for another, you have to use the general ones with their first argument.
An important clarification: the map* helpers depend on this, so they do not work in <script setup>. In the Composition API they are not needed: computed and store.dispatch do the same job just as concisely.
- Composition API and Options API equivalents
| Need | <script setup> |
Options API |
|---|---|---|
| Accessing the store | const store = useStore() |
this.$store |
| Reading state | computed(() => store.state.rooms.list) |
...mapState('rooms', { rooms: 'list' }) in computed |
| Reading a getter | computed(() => store.getters['rooms/availableRooms']) |
...mapGetters('rooms', ['availableRooms']) in computed |
| Getter with an argument | computed(() => store.getters['rooms/roomById'](id)) |
...mapGetters('rooms', ['roomById']) and this.roomById(this.id) |
| Dispatching an action | store.dispatch('bookings/cancelBooking', id) |
...mapActions('bookings', ['cancelBooking']) in methods |
| Committing a mutation | store.commit('rooms/setCatalogView', v) |
...mapMutations('rooms', ['setCatalogView']) in methods |
v-model on the store |
computed({ get, set }) |
A computed with get() and set() in computed |
| Loading on creation | store.dispatch(...) in the script |
created() { this.loadRooms() } |
| Several helpers for one module | — | createNamespacedHelpers('bookings') |
- Good practice: connected views and presentational components
Not every component should know about the store. A common division, which Colmena already follows quite naturally:
| Connected views (containers) | Presentational components | |
|---|---|---|
| Examples in Colmena | RoomsView, BookingView, DashboardBookingsView, AppHeader |
RoomCard, RoomList, RoomFilters, BookingForm, StatusBadge, BaseButton |
| Do they use the store? | Yes: they read state and dispatch actions | No: they receive props and emit events |
| Responsibility | Coordinating: which data, what to do with each event | Displaying and capturing interaction |
| Reuse | Low (one specific screen) | High (on any screen, in tests, in another application) |
| To test them | You need a store (or a mocked one) | Passing them props is enough |
The advantages of keeping presentational components free of the store:
- They can be reused with other data:
RoomListcan render the catalogue's rooms or those from a search result. - They are easy to test: mount
RoomCardwith a sample room, without preparing any store. - The data flow is visible: by looking at the view's template, you know which data each component receives.
AppHeader is an in-between case: technically it is a component, but it occupies a fixed place in the application's frame and is not reused; connecting it to the store is reasonable. BookingForm, on the other hand, currently injects the session; when we remove the provide, we will pass it the session as a prop from its view so that it remains a presentational component.
- Case study: connecting Colmena to the store
9.1 The catalogue view preference, into the store
Today, the view chosen in the catalogue (grid, table or map) is a local ref in RoomsView: if you open a room's spec sheet and come back, it is lost. It is a preference that must outlive the view, so we move it into the rooms module. In src/store/modules/rooms.js:
// In state: add the preference
state: () => ({
list: [],
loadedAt: null,
loading: false,
error: null,
catalogView: 'grid' // 'grid' | 'table' | 'map'
}),
// In mutations
setCatalogView(state, view) {
state.catalogView = view
}9.2 HomeView
In the script, delete catalog, loading, error, freeRooms, the onMounted and the import of fetchRooms, and replace them with:
// HomeView.vue
import { computed, inject } from 'vue'
import { useStore } from 'vuex'
import { CONFIG_KEY } from '@/keys.js'
const { centreName, openingHour, closingHour } = inject(CONFIG_KEY)
const store = useStore()
store.dispatch('rooms/loadRooms')
const loading = computed(() => store.state.rooms.loading)
const error = computed(() => store.state.rooms.error)
const freeRooms = computed(() => store.getters['rooms/availableRooms'].length)The template does not change: it uses the same names. Note that the centre's configuration still arrives through inject: it is immutable context data, not shared state.
9.3 RoomsView
This is the view that gets simplified the most. In the script, delete the catalogue block: catalog, loading, error, loadRooms, the floorFilter watch with its AbortController, reloadRooms and the currentView ref, together with any imports that are no longer used (watch, onWatcherCleanup, fetchRooms). In their place, after the filters' computed properties (because it uses floorFilter), add:
// RoomsView.vue
import { useStore } from 'vuex'
const store = useStore()
store.dispatch('rooms/loadRooms')
const loading = computed(() => store.state.rooms.loading)
const error = computed(() => store.state.rooms.error)
// The whole catalogue is in the store; the floor is filtered here, without asking the API for anything
const catalog = computed(() => {
const all = store.state.rooms.list
return floorFilter.value === null ? all : all.filter((room) => room.floor === floorFilter.value)
})
function reloadRooms() {
store.dispatch('rooms/loadRooms', { force: true })
}
// The chosen view lives in the store: it survives leaving and coming back to the catalogue
const currentView = computed({
get: () => store.state.rooms.catalogView,
set: (view) => store.commit('rooms/setCatalogView', view)
})catalog,loading,error,reloadRoomsandcurrentViewkeep their names, so the rest of the script (freeRooms,catalogEquipment,visibleRooms...) and the template (the states, the Retry button,@click="currentView = key", the<component :is>) do not change.- Changing floor no longer makes a request: the filter is a computed property over the store's catalogue. This is the consequence of the decision we took in 05-02.
currentViewis a writable computed: the template assignscurrentView = keyas before, and thesetcommits the mutation.
9.4 RoomDetailView
The spec sheet requested its room with fetchRoom(id). Now all the information is in the store's catalogue. In the script, delete room, loading, error, notFound, loadRoom, the id watch, otherRooms and the imports of fetchRoom and rooms, and add:
// RoomDetailView.vue
import { useStore } from 'vuex'
const store = useStore()
store.dispatch('rooms/loadRooms')
const loading = computed(() => store.state.rooms.loading)
const error = computed(() => store.state.rooms.error)
// The room from the param: recalculated when id changes (the view is reused between rooms)
const room = computed(() => store.getters['rooms/roomById'](id) ?? null)
// "It does not exist" can only be stated once the catalogue has loaded
const notFound = computed(() => store.state.rooms.loadedAt !== null && room.value === null)
const otherRooms = computed(() => store.state.rooms.list.filter((r) => r.id !== id))
function reload() {
store.dispatch('rooms/loadRooms', { force: true })
}<!-- In the template, the Retry button -->
<BaseButton @click="reload">
<template #icon>↻</template>
Retry
</BaseButton>- There is no longer a request per room, nor an
AbortController, nor awatch:roomis a computed property that depends onid. When you move from Néctar to Polen in "Other rooms", the view is reused,idchanges androomis recalculated instantly, with no waiting. notFounddistinguishes "I don't know yet" (catalogue not loaded) from "it does not exist" (catalogue loaded and that room not in it). Without the first condition,/rooms/nectarwould show the 404 page while loading.- The
watch(room, ...)for the tab title (04-06) stays as it is.
9.5 BookingForm: the session, as a prop
BookingForm injected the session. So that it remains a presentational component, it will receive it as a prop. In its script, delete the inject(SESSION_KEY, ...) (and SESSION_KEY from the keys import; CONFIG_KEY stays) and extend defineProps:
// BookingForm.vue
const { roomId = 'panal', attendees = 1, session } = defineProps({
roomId: String,
attendees: Number,
// Without a session (e.g. in a test), it behaves like an anonymous manager, as before
session: { type: Object, default: () => ({ name: '', role: 'manager' }) }
})isManager, createEmptyForm and the watch(isManager, ...) still read session.role and session.name, now from the prop. The default value keeps the isolated behaviour we had with the inject factory.
9.6 BookingView
Replace the inject(BOOKINGS_KEY) and its import with the store:
// BookingView.vue
import { computed } from 'vue' // add it to the existing import
import { useStore } from 'vuex'
const store = useStore()
const session = computed(() => store.state.session)
const bookingCount = computed(() => store.getters['bookings/activeBookings'].length)
async function createBooking(booking) {
bookingError.value = ''
try {
const created = await store.dispatch('bookings/createBooking', booking)
bookingForm.value.reset()
await router.push({ name: 'dashboard-bookings', query: { new: created.id } })
} catch (error) {
bookingError.value = error.message
}
}<BookingForm
ref="booking-form"
:room-id="roomId"
:attendees="attendees"
:session="session"
@create="createBooking"
/>
<p>
<RouterLink :to="{ name: 'dashboard-bookings' }">View my bookings ({{ bookingCount }})</RouterLink>
</p>9.7 DashboardBookingsView: list, amount and cancellation
The bookings list now reads from the store, loads its data when it is created and gains a button for cancelling:
<script setup>
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import StatusBadge from '@/components/StatusBadge.vue'
import BaseButton from '@/components/base/BaseButton.vue'
const route = useRoute()
const router = useRouter()
const store = useStore()
store.dispatch('bookings/loadBookings')
const bookings = computed(() => store.state.bookings.list)
const loading = computed(() => store.state.bookings.loading)
const error = computed(() => store.state.bookings.error)
const monthTotal = computed(() => store.getters['bookings/monthlyBookingsTotal'])
function roomNameById(id) {
return store.getters['rooms/roomById'](id)?.name ?? id
}
const sortedBookings = computed(() =>
bookings.value.toSorted((a, b) =>
`${a.date} ${a.startTime}`.localeCompare(`${b.date} ${b.startTime}`)
)
)
// New-booking notice (04-05), unchanged
const newBookingId = computed(() => route.query.new ?? null)
const newBooking = computed(() => bookings.value.find((b) => b.id === newBookingId.value))
function closeNotice() {
router.replace({ query: {} })
}
// Cancellation
const cancellingId = ref(null)
const cancellationError = ref('')
async function cancel(booking) {
const confirmed = window.confirm(
`Cancel the booking for the ${roomNameById(booking.roomId)} on ${booking.date}?`
)
if (!confirmed) return
cancellingId.value = booking.id
cancellationError.value = ''
try {
await store.dispatch('bookings/cancelBooking', booking.id)
} catch (e) {
cancellationError.value = `Could not cancel: ${e.message}`
} finally {
cancellingId.value = null
}
}
// Yet another copy of the euro formatter, until the module 7 plugin
const euroFormatter = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR' })
</script>
<template>
<h2>My bookings</h2>
<!-- new-booking notice, unchanged -->
<p>Amount for this month's active bookings: <strong>{{ euroFormatter.format(monthTotal) }}</strong></p>
<p v-if="cancellationError" class="notice" role="alert">{{ cancellationError }}</p>
<p v-if="loading && bookings.length === 0">Loading your bookings…</p>
<p v-else-if="error" class="notice" role="alert">{{ error }}</p>
<p v-else-if="sortedBookings.length === 0">
You have not created any bookings yet.
<RouterLink :to="{ name: 'rooms' }">Find a room in the catalogue</RouterLink>.
</p>
<ul v-else class="booking-list">
<li
v-for="booking in sortedBookings"
:key="booking.id"
:class="{ 'booking-list__new': booking.id === newBookingId }"
>
<StatusBadge :status="booking.status" />
<span>
{{ booking.date }} · {{ booking.startTime }}–{{ booking.endTime }} ·
<RouterLink :to="{ name: 'room-detail', params: { id: booking.roomId } }">
{{ roomNameById(booking.roomId) }}
</RouterLink>
· {{ booking.attendees }} people · {{ booking.member }}
</span>
<BaseButton
v-if="booking.status !== 'cancelled'"
variant="danger"
:disabled="cancellingId === booking.id"
@click="cancel(booking)"
>
{{ cancellingId === booking.id ? 'Cancelling…' : 'Cancel' }}
</BaseButton>
</li>
</ul>
</template>(The styles do not change; add margin-left: auto to the button if you want to align it to the right.)
loading && bookings.length === 0: if there are already bookings (from a previous visit), they are shown while they reload, instead of a loading message.cancellingIdis local state: only this view needs to know which button is busy. Not everything goes into the store.- The cancellation waits for the API (up to 1.5 s) before the badge changes. In 05-05 we will make it optimistic.
9.8 DashboardView, DashboardProfileView and AppHeader
In DashboardView.vue and DashboardProfileView.vue, replace the inject(SESSION_KEY) and its import with:
import { computed } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
const session = computed(() => store.state.session)Their templates (session.name, session.plan, session.role === 'manager') do not change: session is a ref from the script and is unwrapped in the template.
In AppHeader.vue, replace the inject with:
import { computed } from 'vue' // add it to the existing import
import { useStore } from 'vuex'
const store = useStore()
const session = computed(() => store.state.session)
const hasSession = computed(() => store.getters['session/active'])
async function onSignOut() {
if (route.matched.some((record) => record.meta.requiresSession)) {
const failure = await router.push({ name: 'home' })
if (isNavigationFailure(failure)) return
}
await store.dispatch('session/signOut')
}active is no longer in the session's state (it is a getter), so the template uses hasSession.
LoginView was already dispatching session/signIn from 05-03: it does not change.
9.9 App.vue becomes a frame again
With every component connected, the bridges are no longer needed. App.vue ends up like this:
<script setup>
import AppHeader from './components/AppHeader.vue'
</script>
<template>
<AppHeader />
<main class="content">
<RouterView />
</main>
</template>
<style scoped>
/* .content, unchanged */
</style>And src/keys.js keeps only the keys still in use:
If any component still imports SESSION_KEY or BOOKINGS_KEY, Vite will show the error.
9.10 What it would look like in the Options API
In a legacy project, DashboardBookingsView might be written like this. Do not change it in Colmena; it is so that you can recognise the style:
<script>
import { mapState, mapGetters, mapActions, createNamespacedHelpers } from 'vuex'
import StatusBadge from '@/components/StatusBadge.vue'
import BaseButton from '@/components/base/BaseButton.vue'
const bookingsHelpers = createNamespacedHelpers('bookings')
export default {
components: { StatusBadge, BaseButton },
data() {
return { cancellingId: null, cancellationError: '' }
},
computed: {
...bookingsHelpers.mapState({ bookings: 'list', loading: 'loading', error: 'error' }),
...bookingsHelpers.mapGetters({ monthTotal: 'monthlyBookingsTotal' }),
...mapGetters('rooms', ['roomById']),
sortedBookings() {
return this.bookings.toSorted((a, b) =>
`${a.date} ${a.startTime}`.localeCompare(`${b.date} ${b.startTime}`)
)
},
newBookingId() {
return this.$route.query.new ?? null
}
},
created() {
this.loadBookings()
},
methods: {
...bookingsHelpers.mapActions(['loadBookings', 'cancelBooking']),
roomNameById(id) {
return this.roomById(id)?.name ?? id
},
async cancel(booking) {
if (!window.confirm(`Cancel the booking on ${booking.date}?`)) return
this.cancellingId = booking.id
try {
await this.cancelBooking(booking.id) // the method generated by mapActions
} catch (e) {
this.cancellationError = `Could not cancel: ${e.message}`
} finally {
this.cancellingId = null
}
}
}
}
</script>Notice how the helpers bound to bookings are mixed with a general mapGetters('rooms', ...), notice this.$route (the Options API equivalent of useRoute()), and notice that mapState is not used here without a module: all the state is in modules. With the table in section 7, you can translate in both directions.
9.11 Try it
- Navigate from the home page to the catalogue and to a spec sheet with the Network tab open (or with a temporary
console.loginfetchRooms): the catalogue is requested only once. The other views reuse it. - In the catalogue, change floor several times: the results change instantly, with no "Loading…".
- Choose the "Table" view, open a spec sheet and come back: it is still on "Table". In the timeline, you will see the
rooms/setCatalogViewmutation. - On a spec sheet, click several rooms in "Other rooms": they change with no waiting. Type
/rooms/basement: the 404 page appears as soon as the catalogue has loaded. - Sign in as Laura, go to "My bookings" and cancel a booking: the button changes to "Cancelling…" and, after a moment, the badge changes to "Cancelled" and the month's amount is updated.
- Select
Appin the component inspector: it has no state and provides nothing. SelectBookingFormon the booking screen: it receivessessionas a prop. - Search the project for
inject(: only the configuration one remains (inHomeViewandBookingForm).
Common Mistakes and Tips
- Destructuring the state or the getters (
const { list } = store.state.bookings). It loses reactivity. Onecomputedper value. - Using
toRefson the store's state and ending up assigning to thoserefs: the state is modified outside the mutations. - Putting
v-modelon a read-only computed from the store. Use a computed withgetandsetthat commits a mutation. v-modelon properties of a store object (v-model="booking.notes"withbookingfrom the store). It modifies the state directly. Work with a local copy and save with an action.- Calling
useStore()inside a function (a handler, asetTimeout). It must be called at the top level of the script. - Trying to use
mapStateormapActionsin<script setup>. They depend onthis; in the Composition API you usecomputedandstore.dispatch. - Connecting presentational components to the store. They lose reusability and become hard to test. Pass them props from the view.
- Tip: when you refactor a view to use the store, keep the names of the variables the template uses (
catalog,loading,error). The change stays in the script and the template stays the same, as you have seen inRoomsView. - Tip: in legacy Options API code,
createNamespacedHelperscuts down a lot of noise when a component almost always works with the same module.
Exercises
Exercise 1. Translate this Options API component into <script setup>:
import { mapState, mapGetters, mapActions } from 'vuex'
export default {
props: { roomId: String },
computed: {
...mapState('rooms', { loadingRooms: 'loading' }),
...mapGetters('rooms', ['roomById']),
...mapGetters('session', ['isManager']),
room() {
return this.roomById(this.roomId)
}
},
methods: {
...mapActions('rooms', ['loadRooms'])
},
created() {
this.loadRooms()
}
}Exercise 2. Add to the session module an emailNotifications preference (a boolean, true by default) with its mutation, and in DashboardProfileView a "Receive notifications about my bookings by email" checkbox bound with v-model to that preference. Check in the timeline that each click generates a mutation. Do it first in <script setup> and then write only the computed part in the Options API.
Exercise 3. A colleague has written this in AppHeader and says that "the name does not update when I sign in until I reload". Explain why and fix it.
const store = useStore()
const { name, plan } = store.state.session
const active = store.getters['session/active']Solutions
Solution 1.
import { computed } from 'vue'
import { useStore } from 'vuex'
const { roomId } = defineProps({ roomId: String })
const store = useStore()
store.dispatch('rooms/loadRooms') // equivalent to created()
const loadingRooms = computed(() => store.state.rooms.loading)
const isManager = computed(() => store.getters['session/isManager'])
const room = computed(() => store.getters['rooms/roomById'](roomId))roomById does not need its own computed property: it was only used to calculate room. And loadRooms does not need a function of its own if it is only called when the component is created.
Solution 2.
// src/store/modules/session.js
// In createEmptySession() add: emailNotifications: true
// In mutations:
setEmailNotifications(state, enabled) {
state.emailNotifications = enabled
}// DashboardProfileView.vue (<script setup>)
const emailNotifications = computed({
get: () => store.state.session.emailNotifications,
set: (enabled) => store.commit('session/setEmailNotifications', enabled)
})<label>
<input v-model="emailNotifications" type="checkbox" />
Receive notifications about my bookings by email
</label>// Options API
computed: {
emailNotifications: {
get() {
return this.$store.state.session.emailNotifications
},
set(enabled) {
this.$store.commit('session/setEmailNotifications', enabled)
}
}
}By adding the property in createEmptySession(), it exists both with no session and after signing out. Note that setMember only assigns name, email, plan and role, so signing in does not overwrite it. (One detail: the preference is not saved to sessionStorage, so it is lost on reload. We will solve this in a general way in 05-05.)
Solution 3. Destructuring copies the values that name, plan and active had when the header was created (empty, if there was no session). When setMember changes the state, those variables do not notice. When you reload with the session already started, the initial state already has the data, and that is why it "works". The fix:
const store = useStore()
const name = computed(() => store.state.session.name)
const plan = computed(() => store.state.session.plan)
const active = computed(() => store.getters['session/active'])Conclusion
In <script setup>, components access the store with useStore(), read the state and the getters through computed (never by destructuring), dispatch actions for changes that involve logic and commit mutations only for simple preferences. To use v-model on the store, you use a computed with get and set that commits a mutation. In the Options API, the store is in this.$store, and the mapState, mapGetters, mapMutations and mapActions helpers, with the module as their first argument or through createNamespacedHelpers, generate computed properties and methods. And not every component should know about the store: connected views coordinate and presentational components receive props. In Colmena, HomeView, RoomsView, RoomDetailView, BookingView, DashboardView, DashboardProfileView, DashboardBookingsView, LoginView and AppHeader read from the store; the catalogue is requested only once; the catalogue view is remembered; bookings can be cancelled; BookingForm receives the session as a prop, and App.vue no longer provides anything.
The store works, but as soon as it is used intensively new questions appear: cancelling a booking takes more than a second to show up, signing in and opening the dashboard requests the bookings twice, finding a booking by id goes through the whole list, the session's persistence is mixed in with its actions and the modules depend directly on the real API, which will complicate testing. In the next lesson, Advanced Vuex Patterns, we will solve each of these problems with patterns you will find in any professional Vuex application.
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
