Colmena serves members who work in Spanish, Catalan and English, but its interface only speaks English: every text is written directly in the templates, the error messages arrive from the API already worded and, until the previous lesson, each component formatted prices and dates with a hard-coded 'en-GB'. In Creating a Vue.js Plugin we solved that last part: formatPlugin centralises the formats and its locale option accepts a value that can change. Now it is time for the rest. Translating an application is not a matter of swapping some words for others: you have to separate the texts from the code, choose keys that can be maintained, respect each language's word order and plural rules, decide how numbers and dates are formatted, let the user change language without reloading, and avoid making them download languages they do not use. In this lesson you will learn the concepts of internationalisation and localisation, install Vue I18n, the ecosystem's official plugin, in Composition mode, organise the messages into one file per language, use t() and $t with interpolation, pluralisation and formats, interpolate components with <i18n-t>, add a persistent language selector to AppHeader, load languages on demand and translate the error messages from the API and from validation.

Contents

  1. Internationalisation and localisation: concepts
  2. What needs translating in Colmena
  3. Installation and createI18n in Composition mode
  4. The messages: en.json, es.json and ca.json
  5. Translating: t() with useI18n() and $t in templates
  6. Named interpolation
  7. Pluralisation
  8. Number and date formats: n(), d() and formatPlugin
  9. Component interpolation with <i18n-t>
  10. A language selector in AppHeader
  11. Lazy loading of languages
  12. Error messages from the API and from validation
  13. Good practice: keys and concatenation
  14. Going further: routes with a language and <i18n> blocks
  15. Try it

  1. Internationalisation and localisation: concepts

Term What it means In Colmena
Internationalisation (i18n) Preparing the code so that it can work in several languages and regions, without changing it for each one. "i18n" abbreviates the 18 letters between the i and the n of internationalization Taking the texts out of the templates, using keys, formatting with Intl
Localisation (l10n) Adapting the application to a specific language and region: translating texts, formats, conventions Writing ca.json, deciding that English uses British formats
Locale Identifier of a language (and, optionally, a region) according to the BCP 47 standard en, es, ca; for Intl, en-GB, es-ES, ca-ES
Key Stable name of a text, independent of the language menu.rooms
Message The text of a key in a specific language, with slots for data "Floor {floor} · {price}/h"
Fallback language The one used if a translation is missing en
Pluralisation Choosing the form of the message according to a quantity "1 seat left" / "3 seats left"

The central idea is an indirection: the component no longer contains the text but a key, and a separate piece decides which text corresponds to it in the active language.

flowchart LR
    C["Template<br/>$t('menu.rooms')"] --> I["Vue I18n<br/>active language: ca"]
    I --> M{"Does the key exist<br/>in ca.json?"}
    M -->|Yes| T["«Sales»"]
    M -->|No| F["Fallback language (en)<br/>«Rooms» + warning in development"]

  1. What needs translating in Colmena

Before touching any code, it is worth taking stock. Not everything you see on screen is translated in the same way:

Type of text Examples How it is handled
Interface texts Menu, buttons, labels, notices, aria-label, page titles Keys in the message files
Messages with data "Floor 1 · €25.00/h", "Flexible plan" Messages with interpolation
Quantities "3 seats left", "2 fields still need completing or correcting" Pluralisation
Numbers, prices, dates, times €25.00, "Tuesday 3 November" Formats according to the language (formatPlugin)
Domain data with text Name and description of the equipment Keys built from the identifier
Proper names "Colmena Bookings", "Panal Room", "Enjambre Auditorium" Not translated: they are the brand and the names of the rooms
Editorial content The reception note in the header It is not interface: if it must be in several languages, the API must send each version
API errors "The Polen Room is already booked..." The API sends a code; the interface translates it

In this lesson we will translate the most representative pieces (header, room card, booking form, "My bookings", sign-in and errors). The remaining components are translated in exactly the same way; the exercises will suggest a few.

  1. Installation and createI18n in Composition mode

npm install vue-i18n

Vue I18n follows the factory pattern you saw in Using Vue.js Plugins: createI18n(options) returns an object that is both the plugin and the service. Create src/i18n.js (for now, in its simplest version):

// src/i18n.js (first version)
import { createI18n } from 'vue-i18n'
import en from './locales/en.json'
import es from './locales/es.json'
import ca from './locales/ca.json'

export const i18n = createI18n({
  legacy: false, // Composition API (useI18n); "legacy" mode is deprecated
  locale: 'en', // active language
  fallbackLocale: 'en', // fallback language when a translation is missing
  messages: { en, es, ca } // messages for each language
})
  • legacy: false enables Composition mode, the one that goes with <script setup>. Vue I18n carries a "legacy" mode from the Vue 2 era (with this.$i18n and options in each component) that is marked as deprecated; if you omit this option, the console will warn you.
  • locale is the active language. In Composition mode, i18n.global.locale is a ref: changing its .value changes the language of the whole application instantly.
  • fallbackLocale is the language used if a key does not exist in the active one. We use English because it is the language in which the messages are written first, the only one that will always be complete.
  • messages contains one object per language. The JSON files are imported as JavaScript objects thanks to Vite.

In src/main.js, install the plugin alongside our other plugins:

// src/main.js: add the import and the installation
import { i18n } from './i18n.js'

// 2. Language, formatting and directives
app.use(i18n)
app.use(formatPlugin, { locale: 'en-GB', currency: 'EUR' }) // we will connect it to the language in section 8
app.use(directivesPlugin)

With what you learnt in the two previous lessons, you can guess what its install does:

Registers What it is You will use it for
app.provide(...) The translation service useI18n() in <script setup>
globalProperties: $t, $n, $d, $te, $tm, $rt and $i18n Translation and formatting functions Templates and the Options API
Components <i18n-t>, <i18n-n>, <i18n-d> Translation with components inside Section 9
Directive v-t Translation as a directive Rarely; $t is clearer

  1. The messages: en.json, es.json and ca.json

Create the src/locales/ folder with one file per language. The keys are grouped by area of the application, in a tree: menu.rooms is the key rooms inside the group menu. This is the English file, which is the reference:

{
  "app": {
    "title": "Colmena Bookings",
    "subtitle": "Room booking for the Colmena coworking space · {date}"
  },
  "menu": {
    "main": "Main",
    "home": "Home",
    "rooms": "Rooms",
    "dashboard": "My dashboard",
    "signIn": "Sign in",
    "signOut": "Sign out",
    "plan": "{plan} plan",
    "profile": "My profile",
    "bookings": "My bookings",
    "invoices": "Invoices",
    "language": "Language"
  },
  "plans": { "flexible": "Flexible", "fixed": "Fixed", "business": "Business" },
  "card": {
    "floor": "Floor {floor} · {price}/h",
    "equipment": "Equipment:",
    "freeSeats": "No seats left | {n} seat left | {n} seats left",
    "full": "Room full as of {time}!",
    "select": "Select",
    "selected": "Selected",
    "book": "Book"
  },
  "equipment": {
    "projector": { "name": "Projector", "description": "Full HD projector with HDMI and USB-C connections. The remote control is in the room." },
    "whiteboard": { "name": "Whiteboard", "description": "2-metre whiteboard with markers and an eraser." },
    "screen": { "name": "Screen", "description": "55-inch screen with a wireless connection for sharing your laptop." },
    "videoconference": { "name": "Video conferencing", "description": "Wide-angle camera with a speaker and table microphone, compatible with the usual apps." },
    "microphone": { "name": "Microphone", "description": "Two wireless handheld microphones and one lapel microphone, connected to the PA system." }
  },
  "form": {
    "summary": "{room} · {duration} · Estimated price: {price}",
    "invalidTimeSlot": "invalid time slot",
    "pending": "{n} field still needs completing or correcting. | {n} fields still need completing or correcting.",
    "errors": {
      "member": "Tell us who is making the booking.",
      "roomUnavailable": "The {room} is not available.",
      "emptyDate": "Choose a date.",
      "pastDate": "The date cannot be earlier than today.",
      "endTime": "The end time must be later than the start time.",
      "attendees": "Enter a whole number of attendees, at least 1.",
      "capacity": "The {room} holds a maximum of {capacity} people.",
      "notes": "Notes cannot exceed {max} characters.",
      "rules": "You must accept the usage rules."
    }
  },
  "bookings": {
    "title": "My bookings",
    "monthTotal": "Amount for this month's active bookings: {amount}",
    "empty": "You have not created any bookings yet. {link}.",
    "catalogLink": "Find a room in the catalogue",
    "confirmCancellation": "Cancel the booking for the {room} on {date}?",
    "cancellationError": "Could not cancel the booking on {date}: {reason} It has been restored.",
    "cancel": "Cancel",
    "cancelling": "Cancelling…"
  },
  "errors": {
    "api": {
      "connection": "Could not connect to the Colmena server.",
      "roomNotFound": "No room exists with the id “{roomId}”.",
      "roomUnavailable": "The {room} is not accepting bookings at the moment.",
      "invalidTimeSlot": "The end time must be later than the start time.",
      "overlap": "The {room} is already booked on {date} from {start} to {end}.",
      "bookingNotFound": "Booking “{id}” does not exist.",
      "credentials": "Incorrect email or password.",
      "unknown": "An unexpected error has occurred. Please try again."
    }
  }
}

Notice three elements of the message syntax, which you will see in the following sections: {name} marks a slot for a piece of data, | separates the forms of a plural and {n} is the quantity in plurals.

es.json and ca.json have exactly the same structure: the same keys, different texts. Create them by copying en.json and replacing each value with the one in this table:

Key es.json ca.json
app.title Colmena Bookings Colmena Bookings
app.subtitle Reserva de salas del coworking Colmena · {date} Reserva de sales del coworking Colmena · {date}
menu.main Principal Principal
menu.home Inicio Inici
menu.rooms Salas Sales
menu.dashboard Mi panel El meu panell
menu.signIn Iniciar sesión Inicia la sessió
menu.signOut Cerrar sesión Tanca la sessió
menu.plan Plan {plan} Pla {plan}
menu.profile Mi perfil El meu perfil
menu.bookings Mis reservas Les meves reserves
menu.invoices Facturas Factures
menu.language Idioma Idioma
plans.flexible / fixed / business flexible / fijo / empresa flexible / fix / empresa
card.floor Planta {floor} · {price}/h Planta {floor} · {price}/h
card.equipment Equipamiento: Equipament:
card.freeSeats Ninguna plaza libre | Queda {n} plaza libre | Quedan {n} plazas libres Cap plaça lliure | Queda {n} plaça lliure | Queden {n} places lliures
card.full ¡Sala completa desde las {time}! Sala completa des de les {time}!
card.select Seleccionar Selecciona
card.selected Seleccionada Seleccionada
card.book Reservar Reserva
equipment.projector Proyector · Proyector Full HD con conexión HDMI y USB-C. El mando está en la sala. Projector · Projector Full HD amb connexió HDMI i USB-C. El comandament és a la sala.
equipment.whiteboard Pizarra · Pizarra blanca de 2 metros con rotuladores y borrador. Pissarra · Pissarra blanca de 2 metres amb retoladors i esborrador.
equipment.screen Pantalla · Pantalla de 55 pulgadas con conexión inalámbrica para compartir el portátil. Pantalla · Pantalla de 55 polzades amb connexió sense fil per compartir el portàtil.
equipment.videoconference Videoconferencia · Cámara gran angular con altavoz y micrófono de mesa, compatible con las aplicaciones habituales. Videoconferència · Càmera gran angular amb altaveu i micròfon de taula, compatible amb les aplicacions habituals.
equipment.microphone Micrófono · Dos micrófonos inalámbricos de mano y uno de solapa, conectados a la megafonía. Micròfon · Dos micròfons sense fil de mà i un de solapa, connectats a la megafonia.
form.summary {room} · {duration} · Precio estimado: {price} {room} · {duration} · Preu estimat: {price}
form.invalidTimeSlot horario no válido horari no vàlid
form.pending Falta {n} dato por completar o corregir. | Faltan {n} datos por completar o corregir. Falta {n} dada per completar o corregir. | Falten {n} dades per completar o corregir.
form.errors.member Indica quién hace la reserva. Indica qui fa la reserva.
form.errors.roomUnavailable {room} no está disponible. {room} no està disponible.
form.errors.emptyDate Elige una fecha. Tria una data.
form.errors.pastDate La fecha no puede ser anterior a hoy. La data no pot ser anterior a avui.
form.errors.endTime La hora de fin debe ser posterior a la de inicio. L'hora de finalització ha de ser posterior a la d'inici.
form.errors.attendees Indica un número entero de asistentes, como mínimo 1. Indica un nombre enter d'assistents, com a mínim 1.
form.errors.capacity {room} admite como máximo {capacity} personas. {room} admet com a màxim {capacity} persones.
form.errors.notes Las notas no pueden superar los {max} caracteres. Les notes no poden superar els {max} caràcters.
form.errors.rules Debes aceptar las normas de uso. Has d'acceptar les normes d'ús.
bookings.title Mis reservas Les meves reserves
bookings.monthTotal Importe de las reservas activas de este mes: {amount} Import de les reserves actives d'aquest mes: {amount}
bookings.empty Todavía no has creado ninguna reserva. {link}. Encara no has creat cap reserva. {link}.
bookings.catalogLink Busca una sala en el catálogo Cerca una sala al catàleg
bookings.confirmCancellation ¿Cancelar la reserva de {room} del {date}? Vols cancel·lar la reserva de {room} del {date}?
bookings.cancellationError No se ha podido cancelar la reserva del {date}: {reason} Se ha restaurado. No s'ha pogut cancel·lar la reserva del {date}: {reason} S'ha restaurat.
bookings.cancel Cancelar Cancel·la
bookings.cancelling Cancelando… S'està cancel·lant…
errors.api.connection No se ha podido conectar con el servidor de Colmena. No s'ha pogut connectar amb el servidor de Colmena.
errors.api.roomNotFound No existe ninguna sala con el identificador «{roomId}». No existeix cap sala amb l'identificador «{roomId}».
errors.api.roomUnavailable {room} no admite reservas en este momento. {room} no admet reserves en aquest moment.
errors.api.invalidTimeSlot La hora de fin debe ser posterior a la de inicio. L'hora de finalització ha de ser posterior a la d'inici.
errors.api.overlap {room} ya está reservada el {date} de {start} a {end}. {room} ja està reservada el {date} de {start} a {end}.
errors.api.bookingNotFound No existe la reserva «{id}». No existeix la reserva «{id}».
errors.api.credentials Correo o contraseña incorrectos. Correu o contrasenya incorrectes.
errors.api.unknown Se ha producido un error inesperado. Inténtalo de nuevo. S'ha produït un error inesperat. Torna-ho a provar.

(In the table, the equipment rows show name · description, and \| is the plural separator |, escaped for the table.)

Look at menu.plan: "{plan} plan" in English, "Plan {plan}" in Spanish and "Pla {plan}" in Catalan. Word order changes between languages, which is why the slot is part of the message instead of concatenating the plan name + "plan" in the code. We will come back to this in section 13.

  1. Translating: t() with useI18n() and $t in templates

There are two ways of asking for a translation, which follow the rule from 07-02: $t in templates, useI18n() when the script needs it too.

<!-- In any template: $t, registered by the plugin -->
<RouterLink :to="{ name: 'rooms' }">{{ $t('menu.rooms') }}</RouterLink>
// In <script setup>: the composable
import { useI18n } from 'vue-i18n'

const { t, locale } = useI18n()
const label = computed(() => t('menu.rooms')) // reactive: recalculated when the language changes
  • useI18n(), with no arguments, returns the application's global translator. Like every composable that injects, it must be called at the top level of setup.
  • t(key) returns the text in the active language. Internally it reads the language ref, so any template or computed property that calls it is re-evaluated when the language changes.
  • Be careful about storing the result in a constant: const label = t('menu.rooms') is evaluated once and will never change. Call t in the template, in a computed property or at the moment you need the text.

Let us start with the header. In the template of src/components/AppHeader.vue:

<!-- AppHeader.vue: the subtitle and the main menu -->
<p>{{ $t('app.subtitle', { date: format.date(today) }) }}</p>

<nav class="header__menu" :aria-label="$t('menu.main')">
  <RouterLink :to="{ name: 'home' }">{{ $t('menu.home') }}</RouterLink>
  <RouterLink :to="{ name: 'rooms' }">{{ $t('menu.rooms') }}</RouterLink>
  <RouterLink :to="{ name: 'dashboard' }">{{ $t('menu.dashboard') }}</RouterLink>
</nav>

And in the user menu from 06-02:

<p class="user-menu__plan">{{ $t('menu.plan', { plan: $t(`plans.${session.plan}`) }) }}</p>
<ul>
  <li><RouterLink :to="{ name: 'dashboard-profile' }">{{ $t('menu.profile') }}</RouterLink></li>
  <li><RouterLink :to="{ name: 'dashboard-bookings' }">{{ $t('menu.bookings') }}</RouterLink></li>
  <li v-if="session.isManager">
    <RouterLink :to="{ name: 'dashboard-invoices' }">{{ $t('menu.invoices') }}</RouterLink>
  </li>
</ul>
<BaseButton variant="secondary" @click="onSignOut">{{ $t('menu.signOut') }}</BaseButton>

The other texts in the header (the "Sign in" link, the clock buttons) follow the same pattern. The title "Colmena Bookings" is the brand: we leave it as it is.

  1. Named interpolation

The {name} slots are filled with an object as the second argument of t:

t('card.floor', { floor: 1, price: '€25.00' }) // "Floor 1 · €25.00/h"

This is the recommended way of building messages with data: the translator sees the complete sentence, with its named slots, and can place them wherever their language requires. In RoomCard.vue:

<!-- RoomCard.vue -->
<p>{{ $t('card.floor', { floor: room.floor, price: format.price(room.hourlyPrice) }) }}</p>

The validation rules in BookingForm are the clearest case. The errors computed property from 02-09 returned fixed texts; now it returns translations:

// BookingForm.vue
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

const errors = computed(() => {
  const result = {}
  const room = formRoom.value

  if (form.member === '') {
    result.member = t('form.errors.member')
  }
  if (!room.available) {
    result.roomId = t('form.errors.roomUnavailable', { room: room.name })
  }
  // ... date (emptyDate / pastDate), endTime and rules, the same way: t('form.errors.<key>')
  if (!Number.isInteger(form.attendees) || form.attendees < 1) {
    result.attendees = t('form.errors.attendees')
  } else if (form.attendees > room.capacity) {
    result.attendees = t('form.errors.capacity', { room: room.name, capacity: room.capacity })
  }
  if (form.notes.length > 300) {
    result.notes = t('form.errors.notes', { max: 300 })
  }
  return result
})
  • The structure does not change: each rule still adds a property with the field's name. visibleError, focusFirstError and the v-focus directive work as before.
  • Because it is a computed property that calls t, if the member changes language with errors on screen, the messages are translated instantly.
  • {max} instead of writing "300" in the text: if the limit changes, it is changed in one place in the code and not in three language files.

Two characters have a special meaning in messages and need a literal interpolation if you want to show them as they are: @ (Vue I18n uses it for linked messages) and curly braces. A message such as "Write to us at [email protected]" causes a message compilation error; it must be written as "Write to us at reception{'@'}colmena.example".

  1. Pluralisation

Quantities need different forms: "1 seat", "3 seats", and sometimes a special form for zero. In Vue I18n, the forms are separated with | and one is chosen by passing the quantity as the second argument:

// "No seats left | {n} seat left | {n} seats left"
t('card.freeSeats', 0) // "No seats left"
t('card.freeSeats', 1) // "1 seat left"
t('card.freeSeats', 5) // "5 seats left"
Forms in the message How they are chosen (default rule)
Two: singular | plural 1 → singular; 0 and everything else → plural
Three: zero | singular | plural 0 → zero; 1 → singular; 2 or more → plural
  • {n} (or {count}) is filled in automatically with the quantity: there is no need to pass it as a named piece of data as well.
  • If you need other data, pass it in an object and the quantity as the third argument: t('key', { room: 'Polen Room' }, 3).
  • The default rule works for English, Spanish and Catalan, but not for languages with more forms (Russian, Polish or Arabic, for example). For those, createI18n accepts the pluralRules option, with one function per language that decides which form to use.

In RoomCard.vue, replace the free seats paragraph:

<!-- RoomCard.vue: previously "Free seats: <strong>{{ freeSeats }}</strong>" -->
<p>{{ $t('card.freeSeats', freeSeats) }}</p>

And in BookingForm.vue, the hint that in 02-09 we solved with a ternary:

<!-- BookingForm.vue: replaces the errorCount ternary -->
<p v-if="!formIsValid" class="hint">{{ $t('form.pending', errorCount) }}</p>

The ternary worked in English, but each language has its own forms: the decision about which form to use belongs to the message, not to the code.

  1. Number and date formats: n(), d() and formatPlugin

8.1 Vue I18n's formats

Vue I18n also formats numbers and dates, with named formats defined per language in createI18n:

// Example (Colmena does not adopt it, see 8.2)
createI18n({
  // ... legacy, locale, messages ...
  numberFormats: {
    en: { currency: { style: 'currency', currency: 'EUR' } },
    es: { currency: { style: 'currency', currency: 'EUR' } }
  },
  datetimeFormats: {
    en: { long: { weekday: 'long', day: 'numeric', month: 'long' } },
    es: { long: { weekday: 'long', day: 'numeric', month: 'long' } }
  }
})
<p>{{ $n(25, 'currency') }}</p>                     <!-- €25.00 · 25,00 € -->
<p>{{ $d(new Date(2026, 10, 3), 'long') }}</p>      <!-- Tuesday, November 3 · martes, 3 de noviembre -->
  • The options of each format are those of Intl.NumberFormat and Intl.DateTimeFormat: Vue I18n applies them with the active language.
  • Notice the English result: "Tuesday, November 3", in US format, because the language code is en and Intl interprets it as American English. To get the British format, the language would have to be called en-GB throughout the application (files, format keys, selector).

8.2 The decision in Colmena

Colmena already has a formatting service. There are three options:

Option What it involves Assessment
A. Two independent systems formatPlugin stays on 'en-GB' and the texts change language Ruled out: in Spanish you would read "Planta 1 · €25.00/h" and "Tuesday 3 November" inside a Spanish sentence
B. formatPlugin follows Vue I18n's language Its locale option becomes a function that translates the active language into an Intl locale Chosen
C. Replace formatPlugin with n() and d() Rewrite every call and define the formats in createI18n Possible, but more work and a worse result

Why option B:

  • A single source of truth for the language: Vue I18n decides the language; the formatting follows it. They can never get out of sync.
  • formatPlugin handles domain formats that n() and d() do not cover directly: ISO dates interpreted in local time ('2026-11-03'), 'HH:MM' times, durations ("2 hrs 30 mins") and intervals, with its cache of formatters.
  • No component has to be touched: the dozens of calls to $format and format from the previous lesson stay as they are.
  • The language → region mapping is explicit and lives in a single place: en is formatted as en-GB, European English, consistent with a coworking space in Europe.
  • The currency does not depend on the language: Colmena charges in euros whatever language we speak. The language changes the form (€25.00 / 25,00 €), not the currency. That is why currency remains a fixed option.

This way we make the most of everything: Vue I18n for the texts and formatPlugin, connected to it, for the data. To implement it, add to src/i18n.js, after the imports and before createI18n, the list of languages with their Intl locale, and at the end of the file a function that returns the one for the active language:

// src/i18n.js: add
// Interface languages: message code, name in its own language and Intl locale
export const LANGUAGES = [
  { code: 'en', name: 'English', intl: 'en-GB' },
  { code: 'es', name: 'Español', intl: 'es-ES' },
  { code: 'ca', name: 'Català', intl: 'ca-ES' }
]

// The Intl locale of the active language (for formatPlugin)
export function localeIntl() {
  const active = i18n.global.locale.value
  return LANGUAGES.find((language) => language.code === active)?.intl ?? 'en-GB'
}

And in main.js, connect the plugin:

// src/main.js
import { i18n, localeIntl } from './i18n.js'

app.use(i18n)
app.use(formatPlugin, { locale: localeIntl, currency: 'EUR' }) // a FUNCTION, not its result

It is exactly what we prepared in 07-02: formatPlugin calls toValue(locale) every time it formats; since locale is now a function that reads i18n.global.locale.value, every template that shows a price records that read as a dependency and re-renders when the language changes. Notice that we pass localeIntl without parentheses: if you wrote localeIntl(), the plugin would receive the string 'en-GB' from start-up time and would never change.

One case remains: RoomCard's "Room full as of...!" notice. A watch stored the text in notice at the moment the room filled up, so it would stay in the language of that moment. It is the rule we saw in the previous lesson: store the data, not its representation.

// RoomCard.vue: replaces notice and its watch
const { t } = useI18n()

const fullSince = ref(null) // the instant it filled up (a Date) or null

watch(full, (isFull) => {
  fullSince.value = isFull ? new Date() : null
})

// The text is worked out when it is displayed: it follows the active language
const notice = computed(() =>
  fullSince.value
    ? t('card.full', { time: format.time(fullSince.value, { seconds: true }) })
    : ''
)

The template, which showed {{ notice }}, does not change.

  1. Component interpolation with <i18n-t>

Some messages contain elements, not just text: a link in the middle of a sentence, a word in bold. The usual temptations are bad ones:

  • Splitting the sentence into pieces ($t('empty1'), link, $t('empty2')): the translator does not see the complete sentence, and in another language the link may need to go at the beginning.
  • Putting HTML in the message and using v-html: it mixes translation and markup, and opens the door to the code injection you studied in 06-01. Besides, a RouterLink cannot be written in HTML.

The <i18n-t> component solves the problem: the message has a named slot and the template fills that slot with a Vue slot. In "My bookings", the empty-list message contains a link to the catalogue:

<!-- DashboardBookingsView.vue: "You have not created any bookings yet. {link}." -->
<i18n-t keypath="bookings.empty" tag="p">
  <template #link>
    <RouterLink :to="{ name: 'rooms' }">{{ $t('bookings.catalogLink') }}</RouterLink>
  </template>
</i18n-t>
  • keypath is the message key.
  • tag="p" specifies the element that wraps the result. Without tag, it is rendered with no wrapper.
  • Each <template #name> fills the {name} slot. The slot's content is an ordinary Vue template: it can contain components, links, directives.

The form summary and the month's total highlight the price in bold, so they use the same technique:

<!-- BookingForm.vue: replaces the .price-summary paragraph -->
<i18n-t keypath="form.summary" tag="p" class="price-summary">
  <template #room>{{ formRoom.name }}</template>
  <template #duration>
    {{ durationHours > 0 ? $format.duration(durationHours) : $t('form.invalidTimeSlot') }}
  </template>
  <template #price><strong>{{ $format.price(bookingPrice) }}</strong></template>
</i18n-t>

<!-- DashboardBookingsView.vue: the month's total -->
<i18n-t keypath="bookings.monthTotal" tag="p">
  <template #amount><strong>{{ format.price(monthTotal) }}</strong></template>
</i18n-t>

Attributes that do not belong to the component, such as class, are passed to the element specified in tag.

  1. A language selector in AppHeader

10.1 Changing, remembering and announcing the language

Changing the language means assigning i18n.global.locale.value, but a good selector does a little more:

  1. Remember the choice between visits. It is a device preference, like the catalogue view, so it goes into localStorage (key colmena-language), not into sessionStorage like the session.
  2. Update <html lang>. index.html has said lang="en" since 01-03. Screen readers use that attribute to choose the voice and pronunciation: a Spanish text read with English rules is almost incomprehensible. The browser's automatic translators and CSS hyphenation use it too.
  3. Choose a sensible initial language: the saved one; if there is none, the browser's if it is one of ours; otherwise, English.

Add to src/i18n.js, also before createI18n (which is going to use initialLanguage(); if the constants came after it, the browser would throw a ReferenceError when trying to read them before their declaration):

// src/i18n.js: add, before createI18n
const DEFAULT_LANGUAGE = 'en'
const LANGUAGE_KEY = 'colmena-language'

function isValidLanguage(code) {
  return LANGUAGES.some((language) => language.code === code)
}

// Saved → browser languages → English
export function initialLanguage() {
  let saved = null
  try {
    saved = localStorage.getItem(LANGUAGE_KEY)
  } catch {
    // storage not available (strict private mode): we carry on without it
  }
  const fromBrowser = (navigator.languages ?? []).map((tag) => tag.split('-')[0])
  return [saved, ...fromBrowser].find(isValidLanguage) ?? DEFAULT_LANGUAGE
}

export async function changeLanguage(code) {
  if (!isValidLanguage(code)) code = DEFAULT_LANGUAGE
  i18n.global.locale.value = code
  document.documentElement.lang = code
  try {
    localStorage.setItem(LANGUAGE_KEY, code)
  } catch {
    // without storage, the language lasts until the page is reloaded
  }
}
  • navigator.languages is the user's list of preferred languages, in order (['ca-ES', 'ca', 'es', 'en']). We keep the language part and choose the first one we have.
  • try/catch around localStorage: in some browsers with privacy turned all the way up, accessing it throws an exception. A language preference must not stop the application from starting.
  • changeLanguage is async even though it does not wait for anything yet: in section 11 it will load the language before activating it, and this way its callers are already prepared.

In createI18n, use the initial language instead of the fixed one, and in main.js update <html lang> at start-up:

// src/i18n.js: in createI18n
locale: initialLanguage(),

// src/main.js: just before app.mount('#app')
document.documentElement.lang = i18n.global.locale.value

10.2 The selector

In the script of src/components/AppHeader.vue:

// AppHeader.vue: add
import { useI18n } from 'vue-i18n'
import { LANGUAGES, changeLanguage } from '@/i18n.js'

const { locale } = useI18n()

async function onLanguageChange(event) {
  try {
    await changeLanguage(event.target.value)
  } catch (error) {
    console.error('[AppHeader] Could not change the language:', error)
    event.target.value = locale.value // the selector goes back to the language that is still active
  }
}

In the template, at the end of the header, after the user menu:

<!-- AppHeader.vue -->
<select class="header__language" :value="locale" :aria-label="$t('menu.language')" @change="onLanguageChange">
  <option v-for="language in LANGUAGES" :key="language.code" :value="language.code" :lang="language.code">
    {{ language.name }}
  </option>
</select>
/* In the <style scoped> of AppHeader.vue */
.header__language {
  padding: 0.3rem 0.5rem;
  border: 1px solid var(--color-honey-dark);
  border-radius: 999px;
  background: white;
  font: inherit;
}
  • Each language appears in its own language ("Español", "Català"): someone who does not understand the current interface must be able to recognise theirs. That is why the names are in LANGUAGES and not in the messages, and each <option> has its own lang so that the screen reader pronounces it correctly.
  • :value + @change instead of v-model="locale": v-model would assign the language directly, without going through changeLanguage (no saving the preference, no updating <html lang> and, in the next section, no loading the messages). The selector requests the change; changeLanguage carries it out.
  • :aria-label gives the control a name for screen readers, translated like everything else.

10.3 A trap: v-memo

Change the language with "My bookings" open: the title, the buttons and the total are translated, but the rows of the list are not. The dates stay in the previous language. The cause is the v-memo you put on each <li> in 06-01: Vue only re-renders a row if one of its dependencies changes, and the language was not among them. Add it:

// DashboardBookingsView.vue
import { useI18n } from 'vue-i18n'

const { t, locale } = useI18n()
<!-- DashboardBookingsView.vue: the language, a new v-memo dependency -->
<li
  v-for="booking in visibleBookings"
  :key="booking.id"
  v-memo="[booking.status, isCancelling(booking.id), booking.id === newBookingId, roomNameById(booking.roomId), locale]"
  :class="{ 'booking-list__new': booking.id === newBookingId }"
>

It is a good reminder of why v-memo must be used with care: any new piece of data that the row shows, even if it comes "from outside" like the language, must be added to its dependencies.

  1. Lazy loading of languages

With the first version of i18n.js, the three message files travel in the main bundle, even though each member uses only one. With three languages and few keys this is not serious, but a real application has thousands of messages, and each new language would make everyone's download heavier. The solution is the same one you used with the router's views in 04-02: dynamic imports, which Vite turns into separate files downloaded on demand.

The plan:

  • English is still imported statically: it is the fallback language and must always be there.
  • Spanish and Catalan are loaded with import() the first time they are activated, and registered with setLocaleMessage.
  • The application is mounted once the initial language has been loaded, so that the member does not see the interface in English for a moment.

This is the complete version of src/i18n.js (except for translateError, which you will add in section 12):

// src/i18n.js
// Colmena's internationalisation with Vue I18n (Composition mode)
import { createI18n } from 'vue-i18n'
import en from './locales/en.json' // the fallback language always travels in the bundle

// Interface languages: message code, name in its own language and Intl locale
export const LANGUAGES = [
  { code: 'en', name: 'English', intl: 'en-GB' },
  { code: 'es', name: 'Español', intl: 'es-ES' },
  { code: 'ca', name: 'Català', intl: 'ca-ES' }
]
const DEFAULT_LANGUAGE = 'en'
const LANGUAGE_KEY = 'colmena-language'

// The other languages are downloaded the first time they are used (a separate file for each)
const loaders = {
  es: () => import('./locales/es.json'),
  ca: () => import('./locales/ca.json')
}

export const i18n = createI18n({
  legacy: false,
  locale: DEFAULT_LANGUAGE, // the initial one is activated with changeLanguage() before mounting
  fallbackLocale: DEFAULT_LANGUAGE,
  messages: { en }
})

function isValidLanguage(code) {
  return LANGUAGES.some((language) => language.code === code)
}

// Saved → browser languages → English
export function initialLanguage() {
  let saved = null
  try {
    saved = localStorage.getItem(LANGUAGE_KEY)
  } catch {
    // storage not available: we carry on without it
  }
  const fromBrowser = (navigator.languages ?? []).map((tag) => tag.split('-')[0])
  return [saved, ...fromBrowser].find(isValidLanguage) ?? DEFAULT_LANGUAGE
}

// The Intl locale of the active language (for formatPlugin)
export function localeIntl() {
  const active = i18n.global.locale.value
  return LANGUAGES.find((language) => language.code === active)?.intl ?? 'en-GB'
}

let lastRequest = 0

export async function changeLanguage(code) {
  if (!isValidLanguage(code)) code = DEFAULT_LANGUAGE
  const request = ++lastRequest

  if (!i18n.global.availableLocales.includes(code)) {
    const messagesModule = await loaders[code]() // if the download fails, the promise is rejected
    i18n.global.setLocaleMessage(code, messagesModule.default)
  }
  // If another language was requested while we were downloading, the last one wins
  if (request !== lastRequest) return

  i18n.global.locale.value = code
  document.documentElement.lang = code
  try {
    localStorage.setItem(LANGUAGE_KEY, code)
  } catch {
    // without storage, the language lasts until the page is reloaded
  }
}
  • loaders associates each language with a function that imports it. Writing the full paths (instead of import(`./locales/${code}.json`)) makes it clear which files exist and saves Vite from having to guess.
  • availableLocales lists the languages that already have messages: when going back to a language already used, it is not downloaded again.
  • setLocaleMessage(code, messages) registers a language's messages in the translator. messagesModule.default is the JSON object (JSON files are imported as a default export).
  • lastRequest avoids a race condition like the ones in 02-05: if the member chooses Catalan and then, before the download finishes, Spanish, and the Catalan file arrives later, without this check Catalan would end up active.
  • If the download fails, the promise is rejected before anything changes: the active language is still the previous one and the selector, thanks to onLanguageChange, shows it again.

In main.js, mounting waits for the initial language. This is the complete file, with everything that has arrived during the module:

// src/main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import FloatingVue, { hideAllPoppers } from 'floating-vue'
import 'floating-vue/dist/style.css'
import App from './App.vue'
import router from './router'
import { i18n, initialLanguage, changeLanguage, localeIntl } from './i18n.js'
import { persistence } from './stores/plugins/persistence.js'
import { formatPlugin } from './plugins/format.js'
import { directivesPlugin } from './plugins/directives.js'
import { CONFIG_KEY } from './keys.js'
import './assets/main.css'

const app = createApp(App)

// 1. Application configuration
app.config.errorHandler = (error, instance, info) => {
  console.error('[Colmena Bookings] Unhandled error:', error, '| Source:', info)
}
app.provide(CONFIG_KEY, { centreName: 'Coworking Colmena', openingHour: 8, closingHour: 20 })

// 2. Language, formatting and directives: formatPlugin follows Vue I18n's language
app.use(i18n)
app.use(formatPlugin, { locale: localeIntl, currency: 'EUR' })
app.use(directivesPlugin)

// 3. Third-party plugins: tooltips (07-01)
app.use(FloatingVue, {
  distance: 8,
  themes: { tooltip: { delay: { show: 300, hide: 100 } } }
})
document.addEventListener('keydown', (event) => {
  if (event.key === 'Escape') hideAllPoppers() // WCAG 1.4.13
})

// 4. State and navigation: Pinia before the router (its guards use stores)
const pinia = createPinia()
pinia.use(persistence)
app.use(pinia)
app.use(router)

// 5. Mounting, once the initial language has been loaded (if it fails, in English)
changeLanguage(initialLanguage())
  .catch((error) => console.error('[i18n] Could not load the initial language:', error))
  .finally(() => app.mount('#app'))
  • Gone is the <html lang> line from section 10: changeLanguage now updates it.
  • With .catch and .finally, the application always mounts: if the saved language cannot be downloaded (no connection, for example), it starts in English instead of staying blank.
  • The router has already started the first navigation when it was installed, while the language is downloading; that is not a problem, because nothing is rendered until mount.

  1. Error messages from the API and from validation

The validation errors are already translated (section 6). The API's errors are another problem: createBooking throws errors with messages in English such as "The Polen Room is already booked on 2026-11-03 from 10:00 to 12:00", and the interface displayed them as they were with error.message. A real server should not decide the interface's wording (it does not know what language the user is using); the right thing is for it to send a stable code and the error's data, and for the interface to translate them.

In src/api/simulation.js, extend errorWithStatus and use it for connection failures too:

// src/api/simulation.js
export function failSometimes() {
  if (Math.random() < ERROR_PROBABILITY) {
    throw errorWithStatus('Could not connect to the Colmena server', 503, 'connection')
  }
}

// Error like the ones a server returns: HTTP status, stable code and data for the message
export function errorWithStatus(message, status, code = null, data = {}) {
  const error = new Error(message) // the message is still useful for technical logs
  error.status = status
  error.code = code
  error.data = data
  return error
}

In src/api/bookings.js, each error gives its code and its data (the names match the slots of the errors.api messages):

// src/api/bookings.js, in createBooking
throw errorWithStatus(`No room exists with the id "${data.roomId}"`, 404, 'roomNotFound', { roomId: data.roomId })
// ...
throw errorWithStatus(`The ${room.name} is not accepting bookings at the moment`, 409, 'roomUnavailable', { room: room.name })
// ...
throw errorWithStatus('The end time must be later than the start time', 422, 'invalidTimeSlot')
// ...
throw errorWithStatus(
  `The ${room.name} is already booked on ${conflict.date} from ${conflict.startTime} to ${conflict.endTime}`,
  409,
  'overlap',
  { room: room.name, date: conflict.date, start: conflict.startTime, end: conflict.endTime }
)

// in cancelBooking
throw errorWithStatus(`Booking "${id}" does not exist`, 404, 'bookingNotFound', { id })

And in src/api/session.js (import errorWithStatus from ./simulation.js):

throw errorWithStatus('Incorrect email or password', 401, 'credentials')

Now, a function that turns any error into a text in the active language. Add it at the end of src/i18n.js:

// src/i18n.js: add
// Text of an API error in the active language (a generic one if there is no translation)
export function translateError(error) {
  if (!error) return ''
  const { t, te } = i18n.global
  const key = `errors.api.${error.code}`
  if (error.code && te(key)) return t(key, error.data ?? {})
  if (import.meta.env.DEV) console.warn('[i18n] Untranslated error:', error)
  return t('errors.api.unknown')
}
  • te(key) (translation exists) checks whether the key exists. An unexpected error (a programming mistake, a new code from the API) shows a generic message instead of the raw key, and in development it is logged so that someone translates it.
  • i18n.global is the same translator the components use; that is why this function works outside them.
  • Called during rendering, translateError reads the active language and the template is updated if it changes.

The consequence in the components: store the error, not its message, and translate it when displaying it. In BookingView.vue:

// BookingView.vue
import { translateError } from '@/i18n.js'

const bookingError = ref(null) // previously ref('') with the message

async function createBooking(booking) {
  bookingError.value = null
  try {
    const created = await bookingsStore.createBooking(booking)
    bookingForm.value.reset()
    await router.push({ name: 'dashboard-bookings', query: { new: created.id } })
  } catch (error) {
    bookingError.value = error // the whole object: code and data
  }
}
<p v-if="bookingError" class="notice" role="alert">{{ translateError(bookingError) }}</p>

LoginView follows the same pattern: in submit(), error.value = e instead of e.message, and in the template {{ translateError(error) }}. And the cancellation in DashboardBookingsView stores the date and the error so that the message can be composed when it is displayed:

// DashboardBookingsView.vue
import { translateError } from '@/i18n.js'

const cancellationError = ref(null)

async function cancel(booking) {
  const question = t('bookings.confirmCancellation', {
    room: roomNameById(booking.roomId),
    date: format.date(booking.date)
  })
  if (!window.confirm(question)) return
  cancellationError.value = null
  try {
    await bookingsStore.cancelBooking(booking.id)
  } catch (error) {
    cancellationError.value = { date: booking.date, error }
  }
}
<p v-if="cancellationError" class="notice" role="alert">
  {{ $t('bookings.cancellationError', {
    date: format.date(cancellationError.date),
    reason: translateError(cancellationError.error)
  }) }}
</p>

The useRoomsStore and useBookingsStore stores keep the message in their error state (error.value = e.message). To translate it, apply the same change: store e and use translateError(error) in the views that display it. Bear in mind that the persisted state must not include error objects (Colmena's persistence plugin only saves the bookings and the session, so there is no problem).

  1. Good practice: keys and concatenation

Practice Bad Good Why
Keys by meaning and location, not by text "Book" as the key card.book If the text changes, the key does not; and "Book" may be translated differently depending on the context
Group by area Everything at the top level menu.*, card.*, errors.api.* Everything can be found and duplicates are spotted
Never concatenate sentences n + ' ' + t('seats') + ' ' + t('left') t('card.freeSeats', n) Word order and agreement change between languages
Never concatenate data plan + ' ' + t('menu.plan') t('menu.plan', { plan }) "Flexible plan" / "Plan flexible"
Named slots {0} and {1} {room}, {date} The translator understands what goes in each slot
No HTML in messages "... <a href='/rooms'>...</a>" + v-html <i18n-t> with a slot Security, and the translator does not touch markup
Same text, different keys if the context differs Reusing bookings.cancel for "Cancel" in a dialog One key per use In another language they may be different words
The fallback language always complete Adding keys only to ca.json First in en.json, then in the others A raw key is never shown

Two comments about dynamic keys, such as the equipment ones. In RoomCard, the label and the tooltip from 07-01 now read the messages:

<!-- RoomCard.vue: the equipment labels -->
<span>{{ $t('card.equipment') }}</span>
<!-- ... inside the v-for ... -->
<span v-tooltip="$t(`equipment.${item}.description`)" class="card__chip" tabindex="0">
  {{ $t(`equipment.${item}.name`) }}
</span>

And src/data/equipment.js is deleted (if you did exercise 1 in 07-01, apply the same change in RoomDetailView). Building the key from an identifier is acceptable when the values form a closed, known set (the five items of equipment), but it has two costs: tools that look for unused keys cannot detect them, and if a new identifier arrives, the raw key will be shown (with a warning in the development console). Document in en.json (or in the README) that those keys are used dynamically.

Finally, pay attention to the development warnings: "Not found 'x' key in 'ca' locale messages" indicates a missing translation, and "Fall back to translate 'x' key with 'en' locale" that it has been shown in English. They are your to-do list of pending translations. If they bother you while you are working on something else, the missingWarn and fallbackWarn options of createI18n let you silence them, but do not do so permanently.

  1. Going further: routes with a language and <i18n> blocks

Two techniques you will come across in larger projects, which Colmena does not need for now:

Routes with a language prefix. Instead of storing the language in localStorage, it is included in the URL: /es/rooms, /ca/rooms. Each language thus has its own address, which can be shared and which search engines index separately (with the hreflang tags that indicate the versions of each page). It is implemented with a restricted route param and a guard:

// Outline: the application's routes, under a language prefix
{ path: '/:language(en|es|ca)', children: [ /* home, rooms, dashboard... */ ] }

router.beforeEach((to) => changeLanguage(to.params.language))

It makes sense above all for public sites that need to rank in search engines, usually with server-side rendering (09-06). Colmena is an internal application with a session, and the language is a personal preference: localStorage is enough.

<i18n> blocks in SFCs. With the Vite plugin @intlify/unplugin-vue-i18n, a component can carry its own messages in an <i18n lang="json"> block inside the .vue file, and useI18n() uses them as a local scope. This is useful in component libraries that must travel with their texts. The same Vite plugin also lets you precompile the messages during the build, so that the browser does not have to interpret them.

  1. Try it

  1. First visit. In the browser's tools, Application tab, delete the colmena-language key from Local Storage and reload: the application appears in your browser's language if it is English, Spanish or Catalan, and in English otherwise.
  2. Changing language. Choose "Català" in the selector: the menu, the cards, the buttons and the dates change instantly, without reloading. Inspect <html>: lang="ca". The reception clock keeps working and the header says "dimarts, 3 de novembre" (or today's date).
  3. Formats. Choose "Español": the prices become "25,00 €/h", the date switches to Spanish format ("martes, 3 de noviembre") and the form summary to "2 h". Go back to English: "€25.00/h".
  4. Persistence. With Spanish active, reload: the application starts directly in Spanish, without showing English first.
  5. Lazy loading. With the Network tab open and English active, reload: no language file is downloaded. Choose Catalan: the download of a small file with the messages appears. Go back to English and then to Catalan again: it is not downloaded again.
  6. Plurals. In the catalogue, add attendees to the Celda Booth (1 seat): "1 seat left" becomes "No seats left". In Spanish: "Queda 1 plaza libre" and "Ninguna plaza libre".
  7. Validation. In the booking form, trigger several errors and change language with the messages on screen: they are translated without resubmitting. The hint says "3 fields still need completing or correcting." or "Faltan 3 datos...".
  8. API errors. In Catalan, create a booking that overlaps with r-demo-1: the error appears in Catalan, with the room's name and the times in their place. Set ERROR_PROBABILITY = 1 in simulation.js and reload "My bookings": the connection error is translated too. Set it back to 0.1.
  9. The v-memo. In "My bookings", change language: the dates in the rows are translated. Temporarily remove locale from the v-memo dependencies and repeat: the rows stay in the previous language. Put it back.
  10. A missing translation. Temporarily delete menu.invoices from ca.json: in Catalan, the menu shows "Invoices" (the English text) and the console warns. Restore it.

Common Mistakes and Tips

  • Forgetting legacy: false. The old mode is deprecated, the console warns and useI18n() does not behave as you expect.
  • Storing a translation in a constant (const title = t('menu.rooms') at the top level of the script): it will not change language. Call t in the template or in a computed property.
  • Storing already composed messages in the state (error.value = e.message, a notice as text): they stay in the language of that moment. Store the data and compose the text when displaying it.
  • Using v-model on the language when changing it requires more steps (loading messages, saving the preference, updating <html lang>). Centralise the change in a function.
  • Passing localeIntl() instead of localeIntl to formatPlugin: the plugin receives a fixed string and the formats do not follow the language.
  • Forgetting v-memo, v-once or other caches when adding languages: whatever is not re-rendered is not translated.
  • Writing @, {, } or | unescaped in a message: they are interpreted as syntax. Use literal interpolation: {'@'}.
  • Concatenating sentences and data. Each language orders words and makes them agree in its own way: use complete sentences with named slots.
  • Translating proper names (rooms, brand) or editorial content as if it were interface.
  • Not updating <html lang>: screen readers will read Spanish or Catalan with English rules.
  • Tip: write the message in the fallback language first and then in the others, in the same commit. A key that only exists in one language is a debt that gets forgotten.
  • Tip: when the texts are maintained by people who do not program, there are translation management platforms that read and write these JSON files. Keeping the structure by area and descriptive keys makes that work much easier.

Exercises

Exercise 1. The page titles (the routes' meta.title, used by afterEach for document.title and by Breadcrumbs for the breadcrumbs) are still in English only. Translate them: turn each meta.title into a key (routes.rooms, routes.dashboard...), add the messages and make the tab's title also change when the language changes, without navigating.

Exercise 2. StatusBadge shows the six room and booking statuses with a labels object in English. Translate it into the three languages, removing that object. What advantage does the key you propose have over using the English text directly as the key?

Exercise 3. Review this snippet by a colleague. Find at least five problems and fix them:

<script setup>
import { useI18n } from 'vue-i18n'
const { t, locale } = useI18n()
const title = t('bookings.title')
</script>

<template>
  <h2>{{ title }}</h2>
  <select v-model="locale">
    <option value="en">English</option>
    <option value="es">Spanish</option>
    <option value="ca">Catalan</option>
  </select>
  <p>{{ seats }} {{ seats === 1 ? $t('seat') : $t('seats') }} {{ $t('left') }}</p>
  <p>{{ $t('Write to us at [email protected]') }}</p>
</template>

Solutions

Solution 1. In src/router/index.js, each meta.title becomes a key: meta: { title: 'routes.home' }, 'routes.rooms', 'routes.roomDetail', 'routes.book', 'routes.dashboard', 'routes.profile', 'routes.bookings', 'routes.invoices', 'routes.login', 'routes.notFound'. In en.json:

"routes": {
  "home": "Home", "rooms": "Rooms", "roomDetail": "Room details", "book": "New booking",
  "dashboard": "My dashboard", "profile": "Profile", "bookings": "My bookings", "invoices": "Invoices",
  "login": "Sign in", "notFound": "Page not found"
}

(In es.json: "Inicio", "Salas", "Ficha de sala", "Nueva reserva", "Mi panel", "Perfil", "Mis reservas", "Facturas", "Iniciar sesión", "Página no encontrada". In ca.json: "Inici", "Sales", "Fitxa de la sala", "Nova reserva", "El meu panell", "Perfil", "Les meves reserves", "Factures", "Inicia la sessió", "Pàgina no trobada".)

In the router, a function that works out the title and is used in afterEach and when the language changes:

// src/router/index.js
import { watch } from 'vue'
import { i18n } from '@/i18n.js'

function updateTitle(route) {
  const { t } = i18n.global
  document.title = route.meta.title ? `${t(route.meta.title)} · ${t('app.title')}` : t('app.title')
}

router.afterEach((to, from, failure) => {
  if (failure) return
  updateTitle(to)
})

// When the language changes, the current page's title changes too
watch(i18n.global.locale, () => updateTitle(router.currentRoute.value))

And in Breadcrumbs.vue, where record.meta.title was shown, {{ $t(record.meta.title) }}.

  • afterEach and the watch are outside the components: that is why they use i18n.global, the same translator exported from src/i18n.js.
  • i18n.global.locale is a ref, so watch can watch it directly.
  • RoomDetailView overwrites the title with the room's name (a proper name): that case does not change.

Solution 2. In en.json (and its equivalents in es.json and ca.json):

"statuses": {
  "available": "Available", "full": "Full", "unavailable": "Unavailable",
  "confirmed": "Confirmed", "pending": "Pending", "cancelled": "Cancelled"
}

(Spanish: "Disponible", "Completa", "No disponible", "Confirmada", "Pendiente", "Cancelada". Catalan: "Disponible", "Completa", "No disponible", "Confirmada", "Pendent", "Cancel·lada".)

<!-- StatusBadge.vue: the labels object is deleted -->
<template>
  <span class="badge" :class="`badge--${status}`">{{ $t(`statuses.${status}`) }}</span>
</template>

The dynamic key is acceptable because the prop's validator guarantees a closed set of six values. The advantage of statuses.confirmed over using "Confirmed" as the key: if tomorrow the English text becomes "Confirmed by the centre", the key does not change and the other languages are not left disconnected; moreover, the key reflects the model's identifier (booking.status), which does not depend on any language.

Solution 3.

  1. const title = t(...) is evaluated once: it does not change language. Use $t('bookings.title') in the template (or a computed property).
  2. v-model="locale" changes the language without loading its messages, without saving the preference and without updating <html lang>. Use :value + @change with changeLanguage.
  3. The language names are in English ("Spanish", "Catalan"): someone who does not read English will not find theirs. Each one in its own language, with its lang.
  4. The concatenated sentence (number + seat/seats + left) does not work in other languages and reimplements pluralisation by hand: use a single message with forms, $t('card.freeSeats', seats).
  5. The text as the key ('Write to us at...'): if the text changes, the translation is lost. Use a key such as contact.reception.
  6. The unescaped @: the message fails to compile. In the JSON: "Write to us at reception{'@'}colmena.example".
<script setup>
import { useI18n } from 'vue-i18n'
import { LANGUAGES, changeLanguage } from '@/i18n.js'

const { locale } = useI18n()
</script>

<template>
  <h2>{{ $t('bookings.title') }}</h2>
  <select :value="locale" :aria-label="$t('menu.language')" @change="changeLanguage($event.target.value)">
    <option v-for="language in LANGUAGES" :key="language.code" :value="language.code" :lang="language.code">
      {{ language.name }}
    </option>
  </select>
  <p>{{ $t('card.freeSeats', seats) }}</p>
  <p>{{ $t('contact.reception') }}</p>
</template>

Conclusion

Internationalising means preparing the code for several languages (i18n), and localising means adapting it to each one (l10n). With Vue I18n, created with createI18n in Composition mode (legacy: false, locale, fallbackLocale, messages), the texts move out of the templates into one file per language organised by area (src/locales/en.json, es.json, ca.json) and are requested by key with $t in templates or with t from useI18n() in the script. Messages support named interpolation ({room}), pluralisation with forms separated by | and the quantity in {n}, and components inside them with <i18n-t> and slots. Vue I18n also formats with n() and d(), but in Colmena we have chosen to connect formatPlugin to the active language through localeIntl, so that a single language governs both texts and formats without changing the currency. AppHeader has a selector that calls changeLanguage, which downloads the language if necessary, activates it, updates <html lang> and remembers it in localStorage; the application is mounted once the initial language is ready. API errors now carry a code and some data that translateError turns into a message in the active language, the form validation is translated in its computed property, and we have learnt to name keys by meaning, never to concatenate and not to forget caches such as v-memo.

With this module, Colmena Bookings has brought together many pieces that must fit with one another: three Pinia stores with persistence, a router with guards that consult them, our own directives, our own and third-party plugins, and an interface in three languages downloaded on demand. And you have seen several times how fragile that balance is: a v-memo without the language leaves rows untranslated, a localeIntl() with parentheses freezes the formats, a different order in main.js works by chance. Until now, the only way to know whether a change breaks something has been to go through the application by hand following the steps of each "Try it", and every lesson adds more steps. Colmena has no automatic safety net to warn you, in seconds and without opening the browser, that a change has broken the formatting of a price, a validation rule or an optimistic cancellation. Building one is the goal of the next module, which begins with Unit Testing with Vue Test Utils and Vitest.

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