In the previous lesson you saw how other people's plugins are built internally: Vue Router and Pinia register components, provide services and add global properties from their install method, and Floating Vue is configured with options that it merges with its own. Now it is your turn to write yours. Creating a plugin is not difficult, but doing it well means deciding several things: which options it accepts and what happens if they arrive wrong, through which channel it exposes its functionality (and for whom), where it keeps its state so that two applications do not tread on each other, and how it will be tested. In this lesson you will learn the anatomy of install(app, options), how to provide default values and validate the options, how to choose between provide with a composable, globalProperties, components and directives, the factory pattern, isolation between applications, how a plugin is tested and what it would take to publish it on npm. In Colmena you will create formatPlugin, which centralises the formatting of prices, dates, times and durations with Intl and removes every copy of formatPrice, euroFormatter and formatDate, and directivesPlugin, which takes over the registration of v-focus and v-click-outside. By the end, main.js will be organised by responsibility.
Contents
- Anatomy of
install(app, options) - Options: default values and validation
- Four ways to expose functionality
provideand a composable: the route for<script setup>globalProperties: the route for templates and the Options API- The plugin as a factory
- Isolation: one state per application
- How a plugin is tested
- Publishing a plugin on npm (outline)
- Case study:
formatPlugin - Case study:
directivesPlugin - Goodbye to the formatting copies
- The tidy
main.js - Try it
- Anatomy of
install(app, options)
install(app, options)Every well-written plugin follows the same outline, with more or fewer steps:
export const myPlugin = {
install(app, options = {}) {
// 1. Normalise the options: default values and validation
// 2. Create the state or the service for THIS application
// 3. Expose it: app.provide, app.config.globalProperties, app.component, app.directive
// 4. Register the clean-up, if it creates anything outside Vue: app.onUnmount(...)
}
}Some details of the call to install worth keeping in mind:
| Detail | Consequence |
|---|---|
It runs once per application, when app.use is called |
If two applications install the plugin, install runs twice, once for each app |
| It runs before mounting | There are no components or application DOM yet; do not try to read them |
| Vue ignores what it returns | If install is async, Vue does not wait for it to finish: everything that must exist at mount time has to be done synchronously |
app.version gives the Vue version |
A plugin can check that it is compatible and warn if not |
app.onUnmount(fn) (Vue 3.5+) |
Registers a clean-up that runs when app.unmount() is called |
app.runWithContext(fn) |
Runs fn with access to what the application provides (inject works inside it), even without a component |
A small example that brings the four steps together: a plugin that warns when the internet connection is lost.
// Teaching example (not part of Colmena)
import { ref, readonly } from 'vue'
export const CONNECTION_KEY = Symbol('connection')
export const connectionPlugin = {
install(app, { warn = true } = {}) { // 1. options with a default value
const isOnline = ref(navigator.onLine) // 2. state for THIS application
function update() {
isOnline.value = navigator.onLine
if (warn && !isOnline.value) console.warn('No connection')
}
window.addEventListener('online', update)
window.addEventListener('offline', update)
app.provide(CONNECTION_KEY, readonly(isOnline)) // 3. expose it
app.onUnmount(() => { // 4. clean-up
window.removeEventListener('online', update)
window.removeEventListener('offline', update)
})
}
}- Destructuring with a default value (
{ warn = true } = {}) supports bothapp.use(connectionPlugin)andapp.use(connectionPlugin, { warn: false }). readonlyprevents a component from modifying the plugin's state, just as we did with the session in 03-07.- The clean-up matters in applications that are mounted and unmounted (tests, embedded widgets): without it, the
windowlisteners would outlive the application.
- Options: default values and validation
The options are the plugin's public interface: whoever installs it does not read its code, only its documentation. That is why they deserve careful handling.
2.1 Default values
The usual approach is to merge an object of default values with what is received:
const DEFAULT_OPTIONS = { locale: 'en-GB', currency: 'EUR' }
const result = { ...DEFAULT_OPTIONS, ...options }There is a catch: if someone passes { locale: undefined } (for example, by reading an environment variable that does not exist), the spread copies the undefined on top of the default value. To avoid this, discard the keys without a value first:
const defined = Object.fromEntries(
Object.entries(options).filter(([, value]) => value !== undefined)
)
const result = { ...DEFAULT_OPTIONS, ...defined }2.2 Validation
A plugin receives its options once, at start-up. That is the best moment to catch mistakes: an immediate, clear failure in main.js is far better than an odd format discovered weeks later on a rarely visited screen. Distinguish between two kinds of problem:
| Problem | Example | Recommended reaction |
|---|---|---|
| Invalid option: the plugin cannot work | currency: 'EURO', locale: 'en_GB' |
Throw an error with a message explaining how to fix it |
| Unknown option: probably a typo | language: 'en-GB' instead of locale |
Warn in development (import.meta.env.DEV) and carry on with the default values |
To validate Intl values, the most reliable approach is to ask Intl itself: Intl.getCanonicalLocales('en_GB') throws a RangeError because language tags use a hyphen, and new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EURO' }) throws another because currency codes have three letters. Catching those errors and rethrowing them with a message of your own, saying which plugin is failing and how to fix it, saves its users a lot of time. You will see this applied in section 10.
- Four ways to expose functionality
A plugin can offer what it does through several channels, and choosing well depends on who is going to use it and from where:
| Channel | Consumed with | For whom | Advantages | Drawbacks |
|---|---|---|---|---|
app.provide + useX() composable |
const x = useX() in the script |
<script setup> and composables |
Explicit dependency (there is an import), works with the Composition API, isolated per application |
It has to be imported in each component |
app.config.globalProperties.$x |
{{ $x... }} in templates, this.$x in the Options API |
Templates and Options API components | No imports; convenient for presentation utilities | Invisible to the script of <script setup>; no types until they are declared (09-02); risk of name collisions |
app.component(name, component) |
<ComponentName /> |
Templates | Components available everywhere | Global registration: always in the bundle; hidden dependencies |
app.directive(name, directive) |
v-name |
Templates | DOM behaviours on any element | The same as global component registration |
The first two channels are not mutually exclusive: many plugins, such as Vue Router (useRouter() and $router) or Vue I18n (useI18n() and $t), offer both over the same service. That is what formatPlugin will do: the same object, accessible as $format in any template and as useFormat() in any script.
provide and a composable: the route for <script setup>
provide and a composable: the route for <script setup>In <script setup> there is no this, so global properties are out of the code's reach. The natural route is the dependency injection you already know: the plugin provides the service from the root, and a composable injects it.
export const FORMAT_KEY = Symbol('format')
// In install:
app.provide(FORMAT_KEY, format)
// The composable the plugin exports
export function useFormat() {
const format = hasInjectionContext() ? inject(FORMAT_KEY, null) : null
if (!format) {
throw new Error('[formatPlugin] useFormat() requires the application to have installed formatPlugin.')
}
return format
}- A
Symbolkey avoids collisions with any otherprovide(03-07). It is exported for special cases (tests,app.runWithContext), but the normal thing is to use the composable. - The composable hides the key: whoever uses the plugin writes
useFormat()and does not need to know there is aninjectunderneath. If the mechanism changed tomorrow, the components would never notice. hasInjectionContext()(Vue 3.3+) tells you whether you are somewhereinjectworks: a component'ssetupor insideapp.runWithContext. Called in an event handler or after anawait, it would returnfalse.- Failing with a clear message when there is no service is better than returning
undefinedand getting, later on, a cryptic "Cannot read properties of undefined (reading 'price')".
globalProperties: the route for templates and the Options API
globalProperties: the route for templates and the Options APIGlobal properties are added to the application's configuration and appear on every component instance:
// In an Options API component
export default {
computed: {
priceText() {
return this.$format.price(this.room.hourlyPrice)
}
}
}Three rules for using them well:
- The
$prefix is the convention for distinguishing what comes from outside ($router,$route,$t) from the component's own data. - Specific names. If two plugins register the same name, the last one wins without warning.
$formatis reasonable within an application; a published plugin should use something less generic. - The component's own members take priority: if a component defines something with the same name, it hides the global property. Another reason for the prefix.
Until Vue with TypeScript, the editor will not know that $format exists or what methods it has: there you will learn to declare it so that you get autocompletion and type checking in templates.
- The plugin as a factory
In the previous lesson you saw that you do not install "Vue Router", but the result of createRouter(options). That pattern, a factory that receives the configuration and returns an object that is both plugin and service, has advantages when the service is needed outside components:
// Factory pattern (alternative; Colmena uses the app.use options)
export function createFormatPlugin(options) {
const format = createFormat(options) // the service exists before it is installed
return {
format, // accessible from any module that imports this object
install(app) {
app.provide(FORMAT_KEY, format)
app.config.globalProperties.$format = format
}
}
}// src/format.js in a project that needed it outside components
export const formatting = createFormatPlugin({ locale: 'en-GB', currency: 'EUR' })
// main.js: app.use(formatting)
// a store: formatting.format.price(amount)Options in app.use(plugin, options) |
Factory createXPlugin(options) |
|
|---|---|---|
| Where it is configured | In the call to app.use |
When the object is created, before installing it |
| Use outside components | Only with app.runWithContext |
Direct: you import the created object |
| Examples | Floating Vue, formatPlugin |
createRouter, createPinia, createI18n |
| When to choose it | The service is only used in components | The service is also used in stores, guards or utilities |
Colmena only uses formatting in components, so the first, simpler form is enough. The factory is the natural evolution if a store ever needed to format a price.
- Isolation: one state per application
Since 01-04 you have known that in Vue 3 each application is independent: a page can have several, and tests create a new one for each case. A plugin must respect this: the state is created inside install, not at the top level of the module.
// WRONG: MODULE state, shared by every application that installs the plugin
let format = null
export const formatPluginBad = {
install(app, options) {
format = createFormat(options) // the second application OVERWRITES the first
app.config.globalProperties.$format = format
}
}
export function useFormatBad() {
return format // returns the one from the LAST application installed, whichever yours is
}Imagine the coworking space embeds a small Colmena widget in English on its public website, on the same page as another application in Spanish: after installing both, useFormatBad() will return the English formatter in both. With provide/inject, on the other hand, each component receives the service from its own application.
flowchart TB
subgraph Bad["State in the module"]
M["let format (just one)"]
A1["App A (es-ES)"] -->|"install: format = A"| M
A2["App B (en-GB)"] -->|"install: format = B (overwrites A)"| M
end
subgraph Good["State in install + provide"]
B1["App A"] -->|"provide"| F1["format A (es-ES)"]
B2["App B"] -->|"provide"| F2["format B (en-GB)"]
end
This is not a theoretical case. If you open Floating Vue's code, you will see that its install does assign(config, options) on a module-level config object: its options are global to the page, and two applications that install it with different options overwrite each other's. For a tooltip library that is an acceptable decision; for a service holding application data, it is not. The problem gets worse with server-side rendering (09-06), where a single process serves many users at once: module state would be shared between requests from different users.
- How a plugin is tested
Testing is covered in module 8; here it is enough to know that good design makes it easier. Split the plugin into two layers:
- The service, a pure function with no Vue (
createFormat(options)). It is tested like any function: you call it and check the result. - The installation (
install), a few lines that connect the service to the application.
// Outline of a test for the service (Vitest, 08-01)
import { createFormat } from '@/plugins/format.js'
test('formats prices in euros with the British locale', () => {
// Careful: in locales such as 'es-ES', Intl separates the figure from the symbol with a NON-BREAKING space (25,00 €)
expect(createFormat({ locale: 'en-GB' }).price(25)).toBe('€25.00')
})And when testing a component that uses $format or useFormat(), you have to install the plugin in the test application, just as in main.js. Vue Test Utils allows this with the global.plugins option:
// Outline: mounting RoomCard with the plugin installed (08-01)
mount(RoomCard, {
props: { room },
global: { plugins: [[formatPlugin, { locale: 'en-GB' }]] }
})Details such as that non-breaking space are a good example of why it pays to test the service with exact values once, and in the components to check only that the text appears.
- Publishing a plugin on npm (outline)
If a plugin proves useful in several projects, it can be published as a package. We will not do this with Colmena, but these are the essential steps:
{
"name": "@colmena/vue-format",
"version": "1.0.0",
"type": "module",
"exports": {
".": "./dist/vue-format.js"
},
"files": ["dist"],
"peerDependencies": {
"vue": "^3.5.0"
},
"license": "MIT"
}peerDependencies, notdependencies: the plugin uses the Vue of the project that installs it. If you declared it as an ordinary dependency, two copies of Vue could end up on the page, with errors that are very hard to diagnose.exportsandfilesdefine what is published and how it is imported.- The build is done with Vite's library mode (
build.libinvite.config.js), markingvueas external so that it is not included in the package. - Semantic versioning: renaming an option is a breaking change and requires a new major version.
- Documentation: a README with the installation, every option with its default value, examples and a changelog. It is what you yourself reviewed when evaluating plugins in 07-01.
- Case study:
formatPlugin
formatPlugin10.1 What we need
Colmena's data formatting is scattered: formatPrice and its euroFormatter appeared in Template Syntax and have been copied into every component that showed a price; formatDate lives in AppHeader; several screens show raw ISO dates (2026-11-03); and 'en-GB' is written by hand in half a dozen files. We want:
| Function | Receives | Returns (with en-GB) |
|---|---|---|
price(amount) |
A number | €25.00 |
date(value, style) |
A date '2026-11-03' or a Date; style long (default), short or numeric |
Tuesday 3 November · 3 Nov 2026 · 03/11/2026 |
time(value, { seconds }) |
A time '10:00' or a Date |
10:00 (or 10:00:00) |
duration(hours) |
Hours, with decimals | 2 hrs, 1 hr 30 mins, 30 mins |
With two options: locale (default 'en-GB') and currency (default 'EUR'). And one requirement with the next lesson in mind: locale must be able to change while the application is running, when the member chooses another language. That is why, as well as a string, it will accept a ref or a function that returns the current locale.
10.2 src/plugins/format.js
Create the src/plugins/ folder and, inside it, format.js:
// src/plugins/format.js
// formatPlugin: prices, dates, times and durations with Intl, consistent across the application.
// app.use(formatPlugin, { locale: 'en-GB', currency: 'EUR' })
// In templates: {{ $format.price(25) }}
// In <script setup>: const format = useFormat()
import { inject, hasInjectionContext, toValue } from 'vue'
export const FORMAT_KEY = Symbol('format')
const DEFAULT_OPTIONS = {
locale: 'en-GB', // a string ('en-GB'), or a ref or a function that returns the current locale
currency: 'EUR' // three-letter ISO 4217 code
}
const DATE_STYLES = {
long: { weekday: 'long', day: 'numeric', month: 'long' }, // Tuesday 3 November
short: { day: 'numeric', month: 'short', year: 'numeric' }, // 3 Nov 2026
numeric: { day: '2-digit', month: '2-digit', year: 'numeric' } // 03/11/2026
}
// --- Options: default values and validation ---
function normalizeOptions(options = {}) {
// Keys whose value is undefined must not overwrite the default values
const defined = Object.fromEntries(
Object.entries(options).filter(([, value]) => value !== undefined)
)
if (import.meta.env.DEV) {
const unknown = Object.keys(defined).filter((key) => !(key in DEFAULT_OPTIONS))
if (unknown.length > 0) {
console.warn(
`[formatPlugin] Unknown options: ${unknown.join(', ')}. ` +
`Valid options are: ${Object.keys(DEFAULT_OPTIONS).join(', ')}.`
)
}
}
const result = { ...DEFAULT_OPTIONS, ...defined }
// The locale can only be validated now if it is a string (a ref or a function is read when used)
if (typeof result.locale === 'string') {
try {
Intl.getCanonicalLocales(result.locale)
} catch {
throw new RangeError(
`[formatPlugin] Invalid locale: "${result.locale}". Use tags such as 'en-GB' (with a hyphen, not an underscore).`
)
}
}
try {
new Intl.NumberFormat('en-GB', { style: 'currency', currency: result.currency })
} catch {
throw new RangeError(
`[formatPlugin] Invalid currency: "${result.currency}". Use an ISO 4217 code, such as 'EUR'.`
)
}
return result
}
// --- Conversion of the formats Colmena uses ---
// 'YYYY-MM-DD' → Date at LOCAL midnight (new Date('2026-11-03') would be UTC midnight)
function toDate(value) {
if (value instanceof Date) return value
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
const [year, month, day] = value.split('-').map(Number)
return new Date(year, month - 1, day)
}
return new Date(value)
}
// 'HH:MM' → Date on an arbitrary day at that time (we only care about the time)
function toTime(value) {
if (value instanceof Date) return value
const [hours, minutes] = String(value).split(':').map(Number)
return new Date(2000, 0, 1, hours, minutes)
}
// --- The service: a pure function, with no components, easy to test ---
export function createFormat(options) {
const { locale, currency } = normalizeOptions(options)
const cache = new Map() // Intl objects are expensive to create: we reuse them
function intl(Constructor, intlOptions) {
const currentLocale = toValue(locale) // if locale is a ref or a function, it is read HERE
const key = `${Constructor.name}|${currentLocale}|${JSON.stringify(intlOptions)}`
if (!cache.has(key)) cache.set(key, new Constructor(currentLocale, intlOptions))
return cache.get(key)
}
return Object.freeze({
// 25 → "€25.00"
price(amount) {
return intl(Intl.NumberFormat, { style: 'currency', currency }).format(amount)
},
// '2026-11-03' or Date → "Tuesday 3 November" (styles: long, short, numeric)
date(value, style = 'long') {
if (!(style in DATE_STYLES)) {
if (import.meta.env.DEV) console.warn(`[formatPlugin] Unknown date style: "${style}"`)
style = 'long'
}
return intl(Intl.DateTimeFormat, DATE_STYLES[style]).format(toDate(value))
},
// '10:00' or Date → "10:00"; with { seconds: true } → "10:00:00"
time(value, { seconds = false } = {}) {
const timeOptions = { hour: '2-digit', minute: '2-digit' }
if (seconds) timeOptions.second = '2-digit'
return intl(Intl.DateTimeFormat, timeOptions).format(toTime(value))
},
// 2.5 (hours) → "2 hrs 30 mins"
duration(hours) {
const totalMinutes = Math.round(hours * 60)
const h = Math.floor(totalMinutes / 60)
const min = totalMinutes % 60
const parts = []
if (h > 0) {
parts.push(intl(Intl.NumberFormat, { style: 'unit', unit: 'hour', unitDisplay: 'short' }).format(h))
}
if (min > 0 || parts.length === 0) {
parts.push(intl(Intl.NumberFormat, { style: 'unit', unit: 'minute', unitDisplay: 'short' }).format(min))
}
return intl(Intl.ListFormat, { type: 'unit', style: 'narrow' }).format(parts)
},
// The locale in use (useful for debugging or for passing it to another API)
get locale() {
return toValue(locale)
}
})
}
// --- The plugin: creates one service PER APPLICATION and exposes it through two channels ---
export const formatPlugin = {
install(app, options) {
const format = createFormat(options)
app.provide(FORMAT_KEY, format) // for useFormat() in <script setup>
app.config.globalProperties.$format = format // for templates and the Options API
}
}
// --- The composable: the route for <script setup> ---
export function useFormat() {
const format = hasInjectionContext() ? inject(FORMAT_KEY, null) : null
if (!format) {
throw new Error(
'[formatPlugin] useFormat() must be called in the setup of a component ' +
'in an application that has installed formatPlugin (app.use(formatPlugin)).'
)
}
return format
}10.3 The decisions, one by one
- Three layers in one file:
createFormat(the service, with no components),formatPlugin(the installation) anduseFormat(access from<script setup>). It is the separation from section 8. normalizeOptionsapplies the default values without letting anundefinedoverwrite them, warns in development about unknown options and throws clear errors for invalid locales and currencies.toValue(locale)(Vue 3.3+) returns the value as is if it is a string,.valueif it is aref, and the result of calling it if it is a function. Thanks to this,localecan be fixed today and dynamic tomorrow without changing the plugin.- The locale is read on every call, inside
intl(). When a template calls$format.price(...)during rendering andlocaleis aref(or a function that reads one), Vue records that read as a dependency: if the locale changes, the component re-renders with the new format. This is the reactivity from 02-02 working in our favour, and it is what we will take advantage of in the next lesson. - The cache of
Intlobjects: creating anIntl.NumberFormatis relatively expensive, and a list of bookings may callpricehundreds of times per render. The key includes the locale, so when the language changes, the formatters for the new one are created (once). toDateavoids a classic mistake:new Date('2026-11-03')interprets the string as UTC midnight; in a time zone west of Greenwich, that is still 2 November. Building the date withnew Date(year, month - 1, day)creates it at local midnight.durationusesIntl.ListFormatwithtype: 'unit'to join the parts the way each language would: "2 hrs 30 mins" in English, "2 h i 30 min" in Catalan. There is a more direct API,Intl.DurationFormat, but it is recent; once every browser you need to support includes it, you will be able to replace these lines.Object.freezeprevents a component from modifying the shared service (format.price = ...).
A detail you will see in the invoices: with en-GB, 1450 is formatted as "€1,450.00", with a thousands separator, and 14500 as "€14,500.00". Do not assume this holds in every language: with es-ES, 1450 comes out as "1450,00 €", without a thousands separator, and 14500 as "14.500,00 €". It is not a mistake: the Spanish convention (reflected in Intl's data) does not separate thousands in four-digit figures.
- Case study:
directivesPlugin
directivesPluginIn Custom Directives we anticipated that the two directives would be packaged "together with the formatting" into a plugin. When designing it, however, we see that they are two different responsibilities: how data is presented is one thing, and how certain DOM elements behave is another. A plugin that does a single thing is easier to understand, test and reuse (another project might want the directives and not the formatting). So there will be two plugins, one line each in main.js.
Create src/plugins/directives.js:
// src/plugins/directives.js
// directivesPlugin: registers Colmena's general-purpose directives
// v-focus, v-focus:if="signal" → focus on mount or when the signal changes
// v-click-outside[.esc]="handler" → click outside the element (or Escape)
import { vFocus } from '@/directives/focus.js'
import { vClickOutside } from '@/directives/clickOutside.js'
export const directivesPlugin = {
install(app) {
app.directive('focus', vFocus)
app.directive('click-outside', vClickOutside)
}
}- The directives stay in
src/directives/, each in its own file and exported with itsvNamename. The plugin only registers them: a component that prefers to import them locally can still do so. - The header comment documents what the plugin registers. It is the information that someone reading a template with
v-click-outside.escwill look for when wondering where it comes from. - No options, because it does not need any for now. Exercise 2 explores a plugin with options.
- Goodbye to the formatting copies
With the plugin installed (you will do it in section 13), go through the components. This is the complete list of what has to be removed:
| File | Removed | Replaced with |
|---|---|---|
components/RoomCard.vue |
euroFormatter, formatPrice; the notice's toLocaleTimeString('en-GB') |
format.price(...); format.time(new Date(), { seconds: true }) |
components/BookingForm.vue |
euroFormatter, formatPrice; the text `${durationHours} h` |
$format.price(...); $format.duration(durationHours) |
views/RoomsView.vue |
euroFormatter, formatPrice (we brought them over from App.vue in 04-02) |
format.price(...) in the spec sheet |
views/RoomDetailView.vue |
euroFormatter, formatPrice |
$format.price(...) |
views/dashboard/DashboardBookingsView.vue |
euroFormatter; the raw ISO dates in the list and in the messages |
format.price(...), format.date(...) and format.time(...) |
views/dashboard/DashboardInvoicesView.vue |
euroFormatter |
$format.price(...) and $format.date(..., 'numeric') |
components/AppHeader.vue |
formatDate |
format.date(today) |
components/catalog/TableView.vue |
The provisional €{{ room.hourlyPrice }} from 03-06 |
$format.price(...) |
components/ReceptionClock.vue |
toLocaleTimeString('en-GB') |
$format.time(now, { seconds: true }) |
A rule for choosing between $format and useFormat() in each component: if only the template needs it, $format (no imports); if the script needs it too, useFormat(), and then use that same format in the template, so that the component has a single way of accessing it.
12.1 Template only
BookingForm.vue: delete euroFormatter and formatPrice from the script. In the template:
<!-- BookingForm.vue: in the options of the room selector -->
{{ room.name }} · {{ room.capacity }} people · {{ $format.price(room.hourlyPrice) }}/h
<!-- BookingForm.vue: the summary -->
<p class="price-summary">
{{ formRoom.name }} ·
{{ durationHours > 0 ? $format.duration(durationHours) : 'invalid time slot' }} ·
Estimated price: <strong>{{ $format.price(bookingPrice) }}</strong>
</p>RoomDetailView.vue: delete the copy from the script (with its comment "yet another copy, until the plugin in module 7") and, in the spec sheet, <dd>{{ $format.price(room.hourlyPrice) }}</dd>.
TableView.vue: in the price column, <td>{{ $format.price(room.hourlyPrice) }}</td>.
DashboardInvoicesView.vue: delete euroFormatter and, in the template:
<p>Outstanding: <strong>{{ $format.price(outstanding) }}</strong></p>
<!-- in each row: -->
<td>{{ $format.date(invoice.date, 'numeric') }}</td>
<!-- ... -->
<td>{{ $format.price(invoice.amount) }}</td>ReceptionClock.vue: instead of storing the time already converted into text, store the instant and leave the formatting to the template:
// ReceptionClock.vue: replaces time and updateTime
const now = ref(new Date())
function updateTime() {
now.value = new Date()
}Storing the data (a Date) instead of its representation (a text in English) is a good habit: the representation can change (language, for example) without touching the state.
12.2 Script and template
RoomCard.vue: delete the // --- Formatting --- block and add:
// RoomCard.vue
import { useFormat } from '@/plugins/format.js'
const format = useFormat()
watch(full, (isFull) => {
notice.value = isFull
? `Room full as of ${format.time(new Date(), { seconds: true })}!`
: ''
})RoomsView.vue: the spec sheet is a computed property in the script, so it needs the composable:
// RoomsView.vue: delete euroFormatter and formatPrice, and add
import { useFormat } from '@/plugins/format.js'
const format = useFormat()
// In specSheet, the price entry:
'Price per hour': format.price(selectedRoom.value.hourlyPrice),AppHeader.vue: formatDate was used in the template and in the receptionNoteHtml computed property from 06-01:
// AppHeader.vue: delete formatDate and add
import { useFormat } from '@/plugins/format.js'
const format = useFormat()
const receptionNoteHtml = computed(() => {
const withPlaceholders = receptionNote
.replaceAll('{{ today }}', format.date(today))
.replaceAll('{{ centre }}', centreName)
return sanitizeHtml(withPlaceholders)
})DashboardBookingsView.vue: the script shows the date in the cancellation messages, so it also uses the composable. Delete euroFormatter and add:
// DashboardBookingsView.vue
import { useFormat } from '@/plugins/format.js'
const format = useFormat()
// In cancel(booking), the two occurrences of ${booking.date} become:
// ${format.date(booking.date)}In the template, the month's total and the content of each <li> (the v-memo from 06-01 does not change):
<p>Amount for this month's active bookings: <strong>{{ format.price(monthTotal) }}</strong></p>
<!-- inside each <li> -->
<span>
{{ format.date(booking.date, 'short') }} ·
{{ format.time(booking.startTime) }}–{{ format.time(booking.endTime) }} ·
<!-- link to the room, attendees and member, unchanged -->
</span>12.3 Checking
From the project root, look for leftovers:
The only matches should be in src/plugins/format.js (the default locale and the currency validation) and in src/main.js (the locale option when installing the plugin). If any other file appears, you have left a copy behind.
- The tidy
main.js
main.jsNow src/main.js can be read as an index of what the application installs, grouped by responsibility. Replace it completely:
// 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 { 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. Our own plugins (they depend on nothing)
app.use(formatPlugin, { locale: 'en-GB', 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, with everything installed
app.mount('#app')- Gone are the imports of
vFocusandvClickOutsideand the two calls toapp.directive:directivesPluginnow registers them. - Each group has a comment explaining why it is there. When internationalisation is added in the next lesson, you will know exactly where it goes and what must come before it.
- The order expresses dependencies: our own plugins and Floating Vue depend on nothing; the router depends on Pinia.
Colmena's structure gains a folder:
src/ ├── directives/ │ ├── focus.js ← vFocus │ └── clickOutside.js ← vClickOutside ├── plugins/ │ ├── format.js ← formatPlugin, useFormat, createFormat, FORMAT_KEY │ └── directives.js ← directivesPlugin ├── ...
- Try it
- Nothing has changed... visibly. Go through the catalogue, a spec sheet, the booking form and "My bookings": the prices look the same as before (
€25.00/h). What has changed is that there is now a single place that formats them. - Readable dates and times. In "My bookings", the dates appear as "3 Nov 2026" instead of
2026-11-03; in "Invoices" (as Marta Vidal, manager), as "01/10/2026", and the outstanding amount as "€1,450.00". - Durations. In the booking form, choose 10:00 to 13:00: the summary shows "3 hrs". Since the form only offers times on the hour, check the case with minutes from the console:
document.querySelector('#app').__vue_app__.config.globalProperties.$format.duration(2.5)returns "2 hrs 30 mins". - A single point of change. In
main.js, temporarily changelocale: 'en-GB'to'es-ES': the whole application shows "25,00 €", "martes, 3 de noviembre" and "2 h 30 min", including the header and the clock. Change it back to'en-GB'. - Validation. Try, one at a time,
locale: 'en_GB',currency: 'EURO'andlanguage: 'en-GB': the first two stop the application from starting, with an error explaining how to fix them; the third shows an unknown-option warning in the console and the application carries on in English. Undo the changes. - The composable in the wrong place. Temporarily call
useFormat()inside a function that runs when a button is clicked: the error explains that it must be called insetup. Undo it. - The directives still work. Open
/login: the focus is on the email field. Open the user menu and close it with a click outside and with Escape. - What the tools see. In Vue DevTools, select a
RoomCard(it usesuseFormat()): its injections section shows the service with the keySymbol(format). A component that only uses$formatin the template, such asTableView, does not show it, because it injects nothing. In the console,document.querySelector('#app').__vue_app__.config.globalProperties.$format.localereturns'en-GB'.
Common Mistakes and Tips
- Storing the plugin's state at the top level of the module. Every application (and every test) shares a single state. Create it inside
installand expose it withprovide. - Merging options with
{ ...defaults, ...options }without filtering outundefined. An option that is present but has no value cancels out the default. - Validating silently, or not validating at all. A clear error at start-up (
[formatPlugin] Invalid currency...) saves hours. And warn about unknown options: they are almost always typos. - Trying to use
$formatin the script of<script setup>. There is nothis: use the composable. AvoidgetCurrentInstance().proxy.$format, which relies on internal details. - Calling the composable outside
setup(in a handler or after anawait). Call it at the top of the script and keep the result, as withuseRouter()or the stores. - Making
installasynchronous in the hope that Vue will wait for it. Vue does not wait: whatever must exist at mount time, register it synchronously. - Storing already formatted text in the state (
time.value = date.toLocaleTimeString('en-GB')). Store the data and format it when displaying it: that way a change of format or language does not force you to recompute the state. - Comparing against an ordinary space in tests. In many locales
Intluses non-breaking spaces, for example between the figure and the symbol ines-ES(25,00 €) or before "AM"/"PM" inen-US. - Tip: one plugin, one responsibility.
formatPluginanddirectivesPluginare two lines inmain.js, but each one can be understood and reused on its own. - Tip: document at the top of the file what the plugin registers (directive names,
$properties, composables). It is the first thing someone who comes across$formatin a template will look for.
Exercises
Exercise 1. Add to formatPlugin a timeRange(start, end) function that returns a time interval, such as "10:00–12:00", using the formatRange method of Intl.DateTimeFormat (so that each language uses its own separator). Use it in the DashboardBookingsView list instead of the two calls to time.
Exercise 2. Registering Floating Vue and the Escape listener takes up seven lines of main.js. Turn it into a plugin of your own in src/plugins/tooltips.js: tooltipsPlugin, which installs Floating Vue with Colmena's options, registers the Escape listener and removes it when the application is unmounted. It must accept a delay option (in milliseconds, 300 by default) for the delay before showing.
Exercise 3. A colleague has written this plugin to show room occupancy as a percentage. Find at least four problems and explain the consequences of each one:
let currentOptions = { decimals: 0 }
export const occupancyPlugin = {
async install(app, options) {
Object.assign(currentOptions, options)
const format = new Intl.NumberFormat('en-GB', {
style: 'percent',
maximumFractionDigits: currentOptions.decimals
})
app.config.globalProperties.percentage = (value) => format.format(value)
}
}
export function usePercentage() {
return (value) => new Intl.NumberFormat('en-GB', { style: 'percent' }).format(value)
}Solutions
Solution 1. In createFormat, next to time:
// '10:00', '12:00' → "10:00–12:00" (the separator depends on the language)
timeRange(start, end) {
return intl(Intl.DateTimeFormat, { hour: '2-digit', minute: '2-digit' })
.formatRange(toTime(start), toTime(end))
},<!-- DashboardBookingsView.vue, inside each <li> -->
{{ format.date(booking.date, 'short') }} · {{ format.timeRange(booking.startTime, booking.endTime) }} ·- It reuses
intl()(with its cache) andtoTime(): the new function fits in three lines because the service already solves the hard part. formatRangechooses the right separator: "10:00–12:00" in British English; withen-US, "10:00 AM – 12:00 PM". Concatenatingtime(start) + '–' + time(end)by hand would give an incorrect result in some languages.
Solution 2.
// src/plugins/tooltips.js
// tooltipsPlugin: Floating Vue with Colmena's configuration (v-tooltip)
// + Escape closes any open tooltips (WCAG 1.4.13)
import FloatingVue, { hideAllPoppers } from 'floating-vue'
import 'floating-vue/dist/style.css'
export const tooltipsPlugin = {
install(app, { delay = 300 } = {}) {
app.use(FloatingVue, {
distance: 8,
themes: { tooltip: { delay: { show: delay, hide: 100 } } }
})
function onKeydown(event) {
if (event.key === 'Escape') hideAllPoppers()
}
document.addEventListener('keydown', onKeydown)
app.onUnmount(() => document.removeEventListener('keydown', onKeydown))
}
}// main.js: replaces block 3
import { tooltipsPlugin } from './plugins/tooltips.js'
app.use(tooltipsPlugin)- A plugin can install others with
app.use: whoever installstooltipsPlugindoes not need to know there is Floating Vue underneath. If the library were changed tomorrow, only this file would change (and the templates, if the new one does not offerv-tooltip). - The stylesheet travels with the plugin. Since
main.jsimportstooltipsPluginbeforemain.css, the order of the styles is preserved. app.onUnmountremoves the listener using the same function that was added (the lesson from 06-02 about clean-up still applies).- Remember what you saw in section 7: Floating Vue's options are global to the page. If two applications installed
tooltipsPluginwith different delays, the second would impose its own on both.
Solution 3.
- State in the module (
currentOptions), and mutated withObject.assignon top of that: the second application that installs the plugin changes the first one's options, and options from one test leak into the next. installis asynchronous for no reason: there is nothing to wait for, and it suggests that Vue will wait, which it does not.- Global property without the
$prefix:percentagemay clash with a prop, a data property or a computed property of the same name in any component (and the component's own one will hide it without warning). - The composable does not use the plugin's service: it creates another formatter, with different options (no
decimals) and no cache. The template and the script of the same component would format differently. It should provide the service withapp.provideand haveusePercentageinject it. 'en-GB'hard-coded: it does not even allow the locale to be configured, and it will not be able to follow the active language.- Options with no default values or validation:
app.use(occupancyPlugin)without options works by chance (Object.assignwithundefineddoes nothing), but{ decimals: -1 }will cause a crypticRangeErrorfromIntlat installation.
Conclusion
A plugin of your own is written with an install(app, options) that normalises the options (default values without letting undefined overwrite them, clear errors for anything invalid and development warnings for anything unknown), creates the service inside install so that each application has its own, exposes it through the appropriate channel and, if it creates anything outside Vue, cleans it up with app.onUnmount. For <script setup>, the route is app.provide with a useX() composable that injects the service and fails with a clear message if it is not installed; for templates and the Options API, app.config.globalProperties with the $ prefix; and app.component and app.directive register global pieces. When the service is needed outside components, the factory pattern (createXPlugin(options)) is the alternative. Separating the pure service from its installation makes testing easier, and publishing the plugin would require declaring Vue as a peerDependency. In Colmena, formatPlugin offers $format and useFormat() with price, date, time and duration based on Intl, with a formatter cache and ISO dates interpreted in local time; it has replaced the copies in RoomCard, BookingForm, RoomsView, RoomDetailView, DashboardBookingsView, DashboardInvoicesView and AppHeader, and the 'en-GB' in ReceptionClock and TableView. directivesPlugin registers v-focus and v-click-outside, and main.js now reads as an index organised by responsibility.
There is one decision in this lesson that has not yet borne fruit: the locale option of formatPlugin accepts a ref or a function, and the plugin reads its value on every call. Today we pass it a fixed 'en-GB', but Colmena serves members who speak Spanish, Catalan and English, and all the interface text is still written in English inside the templates. In Internationalization with Vue I18n you will install the official translation plugin, extract the texts into one file per language, add a language selector and connect that locale to the language each member chooses.
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
