At the end of the directives module we left an observation pending about src/main.js: the application installs pieces from different sources, each in its own way. The router and Pinia come in through app.use, the centre's configuration through app.provide and the directives through app.directive. That first form, app.use, is the entry point for plugins, the mechanism Vue offers for packaging functionality and installing it across an entire application with a single line. Almost the whole Vue ecosystem reaches your project that way: routers, state managers, internationalisation, component libraries, monitoring tools... Knowing what a plugin does internally, in what order to install it and how to decide whether a third-party one is worth adopting is as important as knowing how to use it. In this lesson you will learn what a plugin is and what it can contribute, how app.use works and why the order in main.js matters, exactly what Vue Router and Pinia do when they are installed, how a plugin differs from a composables library or a component library, and what criteria to use when evaluating someone else's. In Colmena you will install your first third-party plugin, Floating Vue, to show the description of each piece of equipment in RoomCard in an accessible tooltip.
Contents
- What a plugin is
- What a plugin can contribute to an application
app.use(plugin, options)and the order inmain.js- The plugins Colmena already uses: Vue Router and Pinia under the hood
- Plugin, composables library or component library
- How to evaluate a third-party plugin
- An overview of component libraries
- Case study: equipment tooltips with Floating Vue
- Conditional installation: development-only plugins
- Try it
- What a plugin is
A plugin is code that adds functionality at application level. It is not a special kind of Vue object, just a very simple convention. Vue accepts two forms:
// Form 1: an object with an install method
const examplePlugin = {
install(app, options) {
// app: the application instance created with createApp()
// options: whatever is passed as the second argument to app.use()
}
}
// Form 2: a function, which plays the role of install
function examplePlugin(app, options) {
// ...
}
// In both cases it is installed the same way
app.use(examplePlugin, { /* options */ })appis the same application instance you studied in Understanding the Vue Instance: Application, Components and Lifecycle: the one withapp.component,app.directive,app.provide,app.config...optionsis any value the plugin wants to receive, usually a configuration object.installruns only once, at the momentapp.useis called, before any component exists.
Put another way: a plugin cannot do anything you could not write by hand in main.js. What it adds is packaging: it gives that code a name and makes it configurable. Compare:
// Without a plugin: main.js does all the work by hand
app.directive('focus', vFocus)
app.directive('click-outside', vClickOutside)
// With a plugin (you will write it in the next lesson): one line whose name explains the intent
app.use(directivesPlugin)flowchart LR
U["app.use(plugin, options)"] --> I["plugin.install(app, options)"]
I --> C["app.component(...)<br/>global components"]
I --> D["app.directive(...)<br/>global directives"]
I --> P["app.provide(...)<br/>injectable values"]
I --> G["app.config.globalProperties<br/>$ properties in templates"]
I --> O["app.use(otherPlugin)<br/>dependencies"]
- What a plugin can contribute to an application
Inside install, the plugin has access to the whole application API. These are the tools that real plugins use:
| Mechanism | What it adds | How it is used afterwards | Real example |
|---|---|---|---|
app.component(name, component) |
Global components | In any template, without importing them | <RouterLink>, <RouterView> |
app.directive(name, directive) |
Global directives | v-name in any template |
Floating Vue's v-tooltip |
app.provide(key, value) |
An injectable service | inject(key), almost always wrapped in a composable |
useRouter(), useI18n() |
app.config.globalProperties.$x |
A property accessible from every template and from this |
{{ $route.path }}, this.$router |
$router, $route, $pinia |
app.use(otherPlugin) |
Other plugins it depends on | Transparent to whoever installs it | An "umbrella" plugin that installs several |
app.config.errorHandler |
Global error handling | Automatic | Error monitoring SDKs |
app.onUnmount(fn) (Vue 3.5+) |
Clean-up when the application is unmounted | Automatic | Removing global listeners |
app.mixin(object) |
Options merged into every component | Automatic | Old Vue 2 plugins; discouraged today |
Notice that the table combines two kinds of contribution:
- Things that appear in templates without being imported: components, directives and
$properties. - Services that code accesses through dependency injection:
providein the plugin andinject(or a composable that wraps it) in the components. It is exactly the mechanism from Component Communication, applied from the root.
app.mixin appears in the table because you will come across it in old code, but it injects options into every component in the application, with no visible sign of where they come from: that is why the Composition API made it unnecessary.
app.use(plugin, options) and the order in main.js
app.use(plugin, options) and the order in main.js3.1 How app.use works
app.use does little more than call install, but with three details worth knowing:
- It returns the application itself, so calls can be chained:
createApp(App).use(pinia).use(router).mount('#app'). In Colmena we prefer one call per line, which is easier to read and to comment. - It avoids installing the same plugin twice in the same application. If you try, in development you will see the warning "Plugin has already been applied to target app." and the second
app.usedoes nothing. - It checks the shape of the plugin. If you pass it something that is neither a function nor an object with
install(for example, you forgot to call a factory:app.use(createPinia)instead ofapp.use(createPinia())), it warns with "A plugin must either be a function or an object with an "install" function.".
There can be several options, although almost every plugin takes a single object:
app.use(plugin) // no options: install(app)
app.use(plugin, { theme: 'dark' }) // install(app, { theme: 'dark' })
app.use(plugin, 'a', 'b') // install(app, 'a', 'b'): unusual, but valid3.2 Always before mount
Everything a plugin registers must exist when the first component is rendered. If you call app.use(router) after app.mount('#app'), the first render has already happened without RouterView or RouterLink, and the console shows "Failed to resolve component: RouterView". The rule is simple: configure, install and, last of all, mount.
3.3 The order between plugins
install runs at the moment of app.use, from top to bottom. So when one plugin depends on another, the dependency goes first. You already have a case in Colmena, which we discussed in Migrating from Vuex to Pinia: Pinia is installed before the router because the router's install triggers the first navigation, and the guards of that navigation call useSessionStore().
sequenceDiagram
participant M as main.js
participant P as Pinia
participant R as Vue Router
participant G as beforeEach
M->>P: app.use(pinia)
P->>P: setActivePinia(pinia): stores now work outside components
M->>R: app.use(router)
R->>R: registers RouterLink/RouterView, $router, $route
R->>G: first navigation (the current URL)
G->>P: useSessionStore(): is there a session?
M->>M: app.mount('#app')
And if you reversed the order? It would probably still work, but by chance: the router runs the guards asynchronously, a moment after app.use(router), and by then the next line would already have installed Pinia. All it takes is for some piece to use a store synchronously during installation (another plugin in between, for example) to get the error "getActivePinia() was called but there was no active Pinia". Do not rely on that luck: the order in main.js should express the dependencies.
Position in main.js |
What goes there | Why |
|---|---|---|
| 1 | createApp(App) and app.config (for example, errorHandler) |
Error handling must exist before anything fails |
| 2 | app.provide for the configuration, plugins with no dependencies |
They depend on nothing |
| 3 | Plugins that depend on others | Their dependency is already installed |
| 4 | The router, usually last | Its install starts navigation, which may use everything above |
| 5 | app.mount('#app') |
Everything is registered before rendering |
- The plugins Colmena already uses: Vue Router and Pinia under the hood
You have spent two modules using two plugins without looking inside them. Reading what they do when they are installed explains many things that have so far seemed like "magic". This is Vue Router's install, simplified from its source code:
// Inside createRouter() (simplified): the router IS a plugin
const router = {
// ... push, replace, beforeEach, currentRoute...
install(app) {
// 1. Global components: this is why you do not import RouterLink or RouterView
app.component('RouterLink', RouterLink)
app.component('RouterView', RouterView)
// 2. Global properties: $router and $route in templates and in the Options API
app.config.globalProperties.$router = router
Object.defineProperty(app.config.globalProperties, '$route', {
enumerable: true,
get: () => currentRoute.value // a getter: always the current route
})
// 3. The first navigation, with the browser's URL
if (isBrowser && !started) {
started = true
push(history.location)
}
// 4. Injectable services: what useRouter() and useRoute() read
app.provide(routerKey, router)
app.provide(routeLocationKey, reactiveRoute)
// 5. Clean-up: when the application is unmounted, stop listening to the history
const originalUnmount = app.unmount
app.unmount = function () {
// ... removes the popstate listeners ...
originalUnmount()
}
}
}And this is Pinia's:
// Inside createPinia() (simplified)
const pinia = {
install(app) {
setActivePinia(pinia) // stores also work outside components
app.provide(piniaSymbol, pinia) // what useXStore() uses internally
app.config.globalProperties.$pinia = pinia
// registers the Pinia panel in Vue DevTools (development only)
// and activates the Pinia plugins registered with pinia.use() before it was installed
},
use(piniaPlugin) { /* ... */ }
}With these two snippets in front of you, many pieces of the course fall into place:
| What you have used | Where it comes from |
|---|---|
<RouterLink> and <RouterView> without importing them |
app.component in the router's install |
useRouter() and useRoute() |
Composables that do inject(routerKey) and inject(routeLocationKey) |
$route in a template |
globalProperties, with a getter that returns the current route |
The console: __vue_app__.config.globalProperties.$pinia (05-06) |
globalProperties.$pinia in Pinia's install |
useSessionStore() inside a router guard |
setActivePinia on installation |
pinia.use(persistence) before app.use(pinia) |
Pinia stores its plugins and activates them when it is installed |
Notice the factory pattern too: you do not install "Vue Router", but the object returned by createRouter(options); you do not install "Pinia", but the result of createPinia(). The options are passed to the factory, and the object it creates is both the plugin and the service you will use in the rest of the code (router.push, router.beforeEach). We will come back to this pattern in Creating a Vue.js Plugin.
- Plugin, composables library or component library
Not everything installed with npm install is a plugin. The ecosystem offers three ways of sharing code, and it is worth telling them apart because they change how the library is integrated:
| Type | How it is integrated | Examples | Advantages | Drawbacks |
|---|---|---|---|---|
| Plugin | app.use(...) once in main.js |
Vue Router, Pinia, Vue I18n, Floating Vue | Centralised configuration; services shared across the whole application | What is global is not visible in the component that uses it; it must also be installed in tests |
| Composables library | import { useX } from '...' in each component |
VueUse (useLocalStorage, onClickOutside, useIntersectionObserver) |
Explicit dependencies; only what is imported is bundled | Not suitable for state or configuration that must be unique in the application |
| Importable component library | import { Component } from '...' |
Reka UI (accessible unstyled components), Naive UI | Explicit, with no global configuration | You have to import on every use (or use an auto-importer) |
Many libraries combine several forms. Floating Vue, which you will install shortly, offers a plugin that registers everything, but it also exports its vTooltip directive and its components so you can use them locally. PrimeVue is configured with app.use (theme, language of its texts), but its components are imported one by one.
An example that will feel familiar: VueUse includes onClickOutside and a vOnClickOutside directive with the same purpose as the v-click-outside you wrote in Custom Directives. Writing our own made sense for learning; in a real project, before writing a generic utility, check whether a maintained and tested version already exists, and decide using the criteria in the next section.
- How to evaluate a third-party plugin
Adding a dependency is easy; removing it two years later, when dozens of components use it, is not. Before installing a plugin, review at least these criteria:
| Criterion | What to check | Where to look | Warning sign |
|---|---|---|---|
| Vue 3 compatibility | That it declares vue in peerDependencies with a ^3.x range |
npm view <package> peerDependencies, the repository's package.json |
It only supports Vue 2, or the Vue 3 version lives in an unpublished "next" branch |
| Maintenance | Date of the latest release, release cadence, issues answered, number of maintainers | npm, the repository (releases, issues, changelog) | No releases for over a year, serious issues unanswered, a single maintainer who no longer replies |
| Size and tree-shaking | How much it adds to the final bundle; whether you can import only what you use (ES modules, sideEffects: false) |
Tools such as bundlephobia or pkg-size, and your own build (npm run build) |
A huge dependency for a small feature; it forces you to import everything |
| SSR | That it does not access window or document on import; whether it offers Nuxt integration |
Its documentation (SSR or Nuxt section) | "window is not defined" errors when rendering on the server (09-06) |
| Types | That it includes TypeScript definitions | .d.ts files in the package, types field |
No types, or types maintained separately and out of date |
| Accessibility | Keyboard use, focus management, ARIA attributes, WAI-ARIA patterns | Its documentation, and above all testing it with a keyboard and a screen reader | Components that only work with a mouse |
| Licence | That it is compatible with your project | The package's license field, the LICENSE file |
Licences with obligations your company does not accept (some copyleft ones), or commercial ones that nobody knows about |
Some criteria can be checked from the terminal without opening the browser:
version = '5.4.0'
peerDependencies = { vue: '^3.2.0', '@nuxt/kit': '^3.2.0 || ^4.0.0 || ^5.0.0-0' }
license = 'MIT'version: the latest one published (yours may be later by the time you follow this lesson).peerDependencies: it needs Vue 3.2 or later, and it mentions@nuxt/kit, a sign that it offers a Nuxt module (in other words, it takes server-side rendering into account).license: MIT, a permissive licence.
Applied to the library we are going to use in Colmena, the criteria come out like this:
| Criterion | Floating Vue | Assessment |
|---|---|---|
| Vue 3 | vue: ^3.2.0 |
Fine (the old Vue 2 version was called v-tooltip) |
| Maintenance | Recent releases, built on Floating UI, a very widely used positioning library | Fine |
| Size | Moderate; it exports its pieces separately | Acceptable for the job it does |
| SSR | Nuxt module | Fine |
| Types | Includes .d.ts |
Fine |
| Accessibility | It also appears on keyboard focus and adds aria-describedby while the tooltip is visible; tooltips are not closed with Escape |
We will solve this ourselves (section 8.6) |
| Licence | MIT | Fine |
No library is perfect. The evaluation is not only for saying yes or no: it also tells you what you will have to complete yourself.
- An overview of component libraries
A special category of plugins is component libraries: dozens of ready-made components (buttons, tables, calendars, dialogs, menus) with a consistent design. These are the best known in the Vue 3 ecosystem:
| Library | Approach | Installation | Strengths | Things to bear in mind |
|---|---|---|---|---|
| PrimeVue | Very broad catalogue, design-agnostic | app.use(PrimeVue, { theme: ... }) and importing each component |
Data tables and complex components; styled or unstyled mode (to use your own classes) | The theming system has its own learning curve |
| Vuetify | Material Design | app.use(createVuetify(...)), with a Vite plugin for on-demand imports |
Very complete, excellent documentation, SSR | Imposes the Material look; large bundle if not imported on demand |
| Element Plus | Desktop applications and admin dashboards | app.use(ElementPlus) or on-demand imports |
Admin forms and tables, very popular | Design aimed mainly at desktop |
| Naive UI | Written in TypeScript, styles generated from JavaScript | Direct import of components, no mandatory app.use |
Excellent types, themes configurable in code, no global CSS file | Its styling system differs from ordinary CSS |
| Quasar | A complete framework on top of Vue | Its own CLI, or a Vite plugin + app.use(Quasar, ...) |
Components, plus builds for SPA, SSR, PWA, mobile and desktop from a single codebase | Adopting it means adopting its way of organising the project |
They all have an MIT licence and an active community. Some tips for choosing:
- Choose one and use it throughout the project. Mixing two component libraries doubles the weight, the styles and the ways of doing the same thing.
- Try first the components you will use most (in Colmena that would be forms, tables and dialogs) with a keyboard and a screen reader, and pay attention to how well they adapt to your design.
- Consider "unstyled" (headless) libraries, such as Reka UI: they provide behaviour and accessibility, and you supply the look. They are a good option when you already have your own visual identity.
Colmena does not adopt any component library: it already has its base components (BaseButton, TextField, BasePanel, StatusBadge) with the coworking space's visual identity, and the only thing it lacks is one specific piece that is hard to get right, tooltip positioning. A specialised library is enough for that.
- Case study: equipment tooltips with Floating Vue
8.1 What we need
RoomCard shows the equipment as text: "Equipment: projector, whiteboard, videoconference". Members often ask at reception exactly what each item includes: does the video conferencing come with a camera? Does the projector have USB-C? We want each item to appear as a small label and, when the mouse hovers over it or the keyboard reaches it, to show its description.
A tooltip looks simple until you have to position it: it must sit next to the element, flip if it does not fit above, stay within the screen, follow the element if the page scrolls and remain on top of everything else. That is exactly the kind of problem worth delegating to a specialised library.
8.2 The data: src/data/equipment.js
Until now, each room's equipment was a list of identifiers ('projector', 'whiteboard'...). We need its display name and its description. Create src/data/equipment.js:
// src/data/equipment.js
// Display name and description of each item of room equipment
export const equipmentItems = {
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.'
}
}
// If an unknown identifier appears, it is shown as is and without a description
export function equipmentData(id) {
return equipmentItems[id] ?? { name: id, description: '' }
}- An object indexed by identifier: looking up the data for
'whiteboard'is immediate (equipmentItems.whiteboard). equipmentDataprotects the interface against unexpected data: if the API adds'speaker'tomorrow before we have updated this file, the card will show "speaker" instead of breaking.
8.3 Installation
Check that it appears in the dependencies of package.json (not in devDependencies: it is used in the member's browser, not only during development).
8.4 Registration in main.js
Add these snippets to src/main.js (the rest stays unchanged):
// src/main.js: the Floating Vue imports go BEFORE main.css
import FloatingVue, { hideAllPoppers } from 'floating-vue'
import 'floating-vue/dist/style.css'
import './assets/main.css'
// ... createApp, errorHandler, provide for the configuration and directives, unchanged ...
// Tooltips (Floating Vue). Global options, merged with the library's own
app.use(FloatingVue, {
distance: 8, // gap in pixels between the element and the tooltip
themes: {
tooltip: {
delay: { show: 300, hide: 100 } // do not show tooltips when the mouse just passes over
}
}
})
// WCAG 1.4.13: the user must be able to dismiss a tooltip without moving the pointer
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') hideAllPoppers()
})
// ... Pinia, router and mount, unchanged ...Let us look at each piece:
import FloatingVue from 'floating-vue'imports the plugin (the default export). Itsinstallregisters thev-tooltipdirective (andv-close-popper, for menus) and theVTooltip,VDropdownandVMenucomponents.import 'floating-vue/dist/style.css': the library does not inject its styles on its own. Without this line, the tooltip is created but appears with no background and in the wrong place. It goes beforemain.cssso that our rules, which load afterwards, can override the library's with the same specificity.- The options are merged with the library's. Floating Vue deep-merges what you pass it with its default configuration: by specifying only
delayin thetooltiptheme, the other values of that theme are kept (placement on top, triggering onhover,focusandtouch, content as text rather than HTML). The default delay is 200 ms to show and 0 to hide; we raise it slightly so that moving the mouse across the catalogue does not fill the screen with tooltips. - The Escape listener completes what the library does not do: according to WCAG success criterion 1.4.13, content that appears on pointer hover or on receiving focus must be dismissible without moving the pointer or the focus, usually with Escape.
hideAllPoppersis a function the library itself exports to close everything it has open. It coexists without problems with the user menu'sv-click-outside.esc: one press of Escape closes both. - The position in
main.js: Floating Vue depends neither on Pinia nor on the router, so it can go before them, alongside the other presentation pieces.
An internal detail worth knowing: the v-tooltip directive renders the tooltips in a small, separate Vue application that the library creates on its own, at the end of <body>. That is why the content of v-tooltip is text, and it cannot contain components from your application (a RouterLink, for example). If you ever need rich content, the library offers the <VTooltip> component, with a slot for the content.
8.5 Using it in RoomCard
In the script of src/components/RoomCard.vue, import the function from the data file:
In the template, replace the paragraph <p>Equipment: {{ room.equipment.join(', ') }}</p> with a list of labels:
<!-- RoomCard.vue: replaces the equipment paragraph -->
<div class="card__equipment">
<span>Equipment:</span>
<ul>
<li v-for="item in room.equipment" :key="item">
<span v-tooltip="equipmentData(item).description" class="card__chip" tabindex="0">
{{ equipmentData(item).name }}
</span>
</li>
</ul>
</div>And the styles:
/* In the <style scoped> of RoomCard.vue */
.card__equipment {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.4rem;
margin: 0.5rem 0;
}
.card__equipment ul {
display: flex;
flex-wrap: wrap;
gap: 0.3rem;
margin: 0;
padding: 0;
list-style: none;
}
.card__chip {
display: inline-block;
padding: 0.1rem 0.6rem;
border: 1px solid var(--color-honey-dark);
border-radius: 999px;
font-size: 0.85rem;
cursor: help; /* signals that there is additional information */
}
.card__chip:focus-visible {
outline: 2px solid var(--color-honey-dark);
outline-offset: 2px;
}Line by line:
v-tooltip="..."receives the text of the tooltip. Like any directive (06-02), its value is a JavaScript expression: here, the item's description. If the value changes, the tooltip is updated.- It also accepts an object, for one-off options:
v-tooltip="{ content: text, placement: 'bottom', delay: 0 }". And the placement can be given with a modifier:v-tooltip.bottom="text". tabindex="0"makes the label focusable with the Tab key. Floating Vue also shows the tooltip on focus, but an ordinary<span>never receives it: withouttabindex, keyboard users would never see the descriptions.- Why not a
<button>? A button announces that it does something when pressed, and these labels do nothing: they only inform. A focusable element with its associated description is more honest. list-style: noneon a<ul>: we keep using a list because that is what it is (screen readers announce "list, 3 items"), even though visually they are labels in a row.- The content is text, not HTML. Floating Vue treats the content as text unless its
htmloption is enabled. If the descriptions ever came from the API with formatting, remember what you learnt in Built-in Directives: before enablinghtml, sanitise withsanitizeHtml.
8.6 How the tooltip looks, and accessibility
The tooltip is not rendered inside RoomCard, but at the end of <body> (so that no overflow: hidden clips it). Therefore, the card's scoped styles do not reach it. To adapt it to Colmena's identity, write the rules in the global stylesheet, src/assets/main.css:
/* src/assets/main.css */
/* Floating Vue tooltips: rendered at the end of <body>, outside the components */
.v-popper--theme-tooltip .v-popper__inner {
max-width: 18rem;
background: var(--color-text);
color: white;
font-size: 0.875rem;
line-height: 1.4;
}The .v-popper--theme-tooltip and .v-popper__inner classes are the ones used by the library's stylesheet; we override only what is necessary.
Let us review the accessibility guidelines for tooltips and how each one is met:
| Guideline | How Colmena meets it |
|---|---|
| It can be shown without a mouse | The labels are focusable (tabindex="0") and the tooltip theme is triggered by focus |
| The screen reader announces the description | While the tooltip is visible, the library adds aria-describedby to the element, pointing to the tooltip |
| It can be dismissed without moving the pointer (WCAG 1.4.13) | Escape calls hideAllPoppers() |
| It stays visible while being read | It is only hidden when the pointer leaves the element or the element loses focus |
| It contains no essential information | It is complementary information; in exercise 1 you will also show it on the room's spec sheet |
| On touch screens | The tooltip theme responds to touch: a tap shows it |
The last row of the table is the most important: a tooltip is an aid, never the only place where information needed to use the application lives.
- Conditional installation: development-only plugins
Some plugins only make sense while you are developing: debugging tools, detailed event logs, automatic accessibility audits... They must not reach members' browsers. There are two ways to achieve this.
Tools that work at the Vite level. The Vue DevTools add-on you configured in Creating Your First Vue Application (vueDevTools() in vite.config.js) is a Vite plugin, not a Vue one: it works on the development server and is not part of the production build. When a tool offers this way of integrating, it is the cleanest.
Vue plugins loaded conditionally. If it is a Vue plugin, use import.meta.env.DEV (which Vite replaces with false in the production build) together with a dynamic import:
// src/main.js (outline; Colmena does not need it for now)
async function start() {
const app = createApp(App)
// ... the usual configuration and plugins ...
if (import.meta.env.DEV) {
// Development only: the module is downloaded separately and never reaches production
const { debugPlugin } = await import('./dev/debug.js')
app.use(debugPlugin)
}
app.mount('#app')
}
start()- The dynamic import (
await import(...)) is the key. With a staticimportat the top of the file, the module would be part of the bundle even if theifnever ran. - Wrapping the start-up in
start()lets you wait for the import before mounting, so that the plugin is installed when the first component is rendered. - The same technique works for other conditions: enabling a feature only for certain clients or in certain environments, by reading a Vite environment variable (10-01).
- Try it
- Tooltips with the mouse. Open the catalogue and hover over the "Video conferencing" label of the Néctar Room: after a short delay its description appears above it. Move the mouse quickly across several labels: the tooltips do not appear unless you stop.
- Automatic placement. Scroll the page until a card sits right against the top edge of the window and hover over a label: the tooltip is placed below, because there is no room above.
- With the keyboard. Go through the catalogue with the Tab key: as you reach each label, its tooltip appears and the focus outline is visible. Press Escape: the tooltip is hidden and the focus stays on the label.
- Accessibility in the inspector. With the tooltip visible, inspect the label: it has
aria-describedbywith the tooltip's identifier, which you will find at the end of<body>. When it is hidden, the attribute disappears. - Without the stylesheet. Temporarily comment out
import 'floating-vue/dist/style.css': the tooltip appears as loose text, in the wrong place. Put it back. - What the plugin registers. In Vue DevTools, inspect the component tree with a tooltip open: you will see a separate application with the library's internal components. In the console,
document.querySelector('#app').__vue_app__.config.globalPropertiesshows$router,$routeand$pinia, added by their plugins. - Double installation. Temporarily duplicate the
app.use(pinia)line inmain.js: the console warns that the plugin had already been applied. Undo the change.
Common Mistakes and Tips
- Calling
app.useafterapp.mount. The first render cannot find the plugin's components or directives ("Failed to resolve component"). Always install everything before mounting. - Passing the factory instead of its result:
app.use(createPinia)instead ofapp.use(createPinia()). Vue warns that the plugin has noinstall. - Installing a plugin before the one it depends on. Sometimes it works by chance and stops working after an innocent change. Pinia before the router; in general, the dependency first.
- Forgetting the library's stylesheet, or importing it after yours: without it the component looks broken; after yours, its rules override yours.
- Trying to style a tooltip with
scoped: it is rendered outside the component. Use the global stylesheet (or:global()if you prefer to keep the rule in the component). - Putting a tooltip on an element that does not receive focus: keyboard users will never see it. Use focusable elements or
tabindex="0". - Keeping essential information only in a tooltip. On mobile, with a keyboard or with a screen reader, it can go unnoticed.
- Installing a component library to use a single component. First consider a specialised library, an unstyled one, or writing it yourself.
- Tip: before adding a dependency, write in the commit message (or in the project documentation) why it was chosen and which alternatives were ruled out. A year from now, someone will thank you.
- Tip: check
npm outdatedfrom time to time and read the changelog before upgrading a plugin to a new major version: options often change.
Exercises
Exercise 1. The equipment description is only in the tooltips, and the accessibility table in section 8.6 says that must not be the only place. In RoomDetailView, replace the "Equipment" row of the spec sheet ({{ room.equipment.join(', ') }}) with a description list containing the name and description of each item, reusing equipmentData.
Exercise 2. A colleague proposes installing vue-agenda-plus (a fictitious package) to show an occupancy calendar in RoomDetailView. This is what they find:
version = '2.8.1'
peerDependencies = { vue: '^2.6.0' }
license = 'GPL-3.0'
last published: 3 years ago · 140 open issues · 1 maintainer
size: 310 kB (minified), no ES modulesEvaluate it with the table in section 6 and write a three- or four-sentence recommendation for the team. What alternatives would you propose?
Exercise 3. This main.js from another project has several problems. Find them and explain the symptom of each one:
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import FloatingVue from 'floating-vue'
import './assets/main.css'
import 'floating-vue/dist/style.css'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.use(createPinia)
app.mount('#app')
app.use(FloatingVue)Solutions
Solution 1. In the script of RoomDetailView.vue:
In the template, the equipment row of the spec sheet:
<dt>Equipment</dt>
<dd>
<dl class="spec-sheet__equipment">
<template v-for="item in room.equipment" :key="item">
<dt>{{ equipmentData(item).name }}</dt>
<dd>{{ equipmentData(item).description }}</dd>
</template>
</dl>
</dd>- A description list (
<dl>) is the right semantic element for term-description pairs, just like the spec sheet that contains it. <template v-for>lets you repeat two sibling elements (<dt>and<dd>) without a wrapper, which would not be valid inside<dl>(02-08).- The spec sheet is the detail page: here it makes sense to show all the information permanently, whereas the catalogue, which must be compact, offers it in tooltips.
Solution 2. Evaluation:
| Criterion | Result |
|---|---|
| Vue 3 | No: it only supports Vue 2.6. Ruled out on that alone |
| Maintenance | Poor: 3 years without releases, many issues, a single maintainer |
| Size | Very large for a calendar, and no ES modules (no tree-shaking) |
| Licence | GPL-3.0: it may impose obligations when distributing the application; this would need checking |
| SSR, types, accessibility | No need to go on: it is already ruled out |
Recommendation: "I do not recommend vue-agenda-plus: it is only compatible with Vue 2, it has had no maintenance for three years, it weighs over 300 kB with no way of importing only what is needed, and its GPL licence requires legal advice. I propose evaluating, with the same criteria, a calendar component from the library the team already knows, or building a simple occupancy view with our own table, since all we need is to show the booked slots for one day". The reasonable alternatives are: a calendar component from a maintained, Vue 3-compatible library, or a simple component of our own if the requirement is small.
Solution 3.
main.cssis imported before the Floating Vue stylesheet: the library's rules, which arrive later, override ours of equal specificity. Symptom: the tooltips do not take on the application's colours.app.use(router)before Pinia: the router'sinstalltriggers the first navigation, whose guards may use stores. Whether it works depends on Pinia being installed before the first guard runs: a fragile order that does not express the dependency. Pinia goes first.app.use(createPinia): the factory is passed, not the plugin. Vue warns that the plugin has noinstall, and no store works.app.use(FloatingVue)aftermount: the first render does not know aboutv-tooltip("Failed to resolve directive: tooltip"), and templates already rendered have no tooltips.
Corrected version:
import FloatingVue from 'floating-vue'
import 'floating-vue/dist/style.css'
import './assets/main.css'
// ...
const app = createApp(App)
app.use(FloatingVue)
app.use(createPinia())
app.use(router)
app.mount('#app')Conclusion
A plugin is an object with an install(app, options) method, or a function with that same signature, which app.use runs once before the application is mounted. Inside install it can register global components and directives, provide services with app.provide, add $ properties with app.config.globalProperties, install other plugins and register clean-up tasks; it does nothing you could not write in main.js, but it packages that code and makes it configurable. Order matters: everything before mount, and dependencies before whatever uses them, such as Pinia before the router, whose install triggers the first navigation. By reading the internals of Vue Router and Pinia you have seen where RouterLink, $route, useRouter() and the stores that work in guards come from, and that both follow the factory pattern (createRouter, createPinia). You have also learnt to tell a plugin apart from a composables library such as VueUse or from importable components, to evaluate a dependency by its compatibility, maintenance, size, SSR, types, accessibility and licence, and to place the major component libraries (PrimeVue, Vuetify, Element Plus, Naive UI, Quasar). In Colmena, Floating Vue shows the description of each item of equipment in RoomCard, with global options in main.js, its stylesheet, our own rules in main.css and an Escape listener that completes its accessibility.
Now that you have seen how other people's plugins are built, you are ready to write your own. Colmena has two clear candidates: the v-focus and v-click-outside directives, which are still registered by hand in main.js, and the price and date formatting, still copied into half a dozen components, each with its own hard-coded 'en-GB'. In Creating a Vue.js Plugin you will turn them into directivesPlugin and formatPlugin, and finally get rid of all those copies.
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
