Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 87 ยท Reusability, Transitions and Styling

Plugins

Learn how Vue 3 plugins work. Write an install function, add global components, directives, properties and provide/inject values, and build a small i18n and toast plugin you can run.

Sooner or later an app needs something that belongs to the whole application rather than to one component: translations, a notification system, a router, a state library, a set of shared base components. A plugin is Vue's way to package that kind of app-wide functionality. It is a piece of code that receives the app, and can register components and directives on it, provide values to every component, or add global properties.

You have probably used plugins already without writing one. app.use(router) installs Vue Router and app.use(pinia) installs Pinia. This lesson shows what happens inside, and you will write two small plugins of your own.

app.use and the install function

A plugin is either an object with an install method or a plain function with the same signature. Vue calls it once, with the app instance and any options you passed to app.use.

JavaScript
const myPlugin = {
  install(app, options) {
    // register things on the app here
  },
};

// the function form is equivalent
function myOtherPlugin(app, options) {
  // ...
}

createApp(App).use(myPlugin, { some: "option" }).use(myOtherPlugin).mount("#app");

app.use() returns the app, so calls can be chained. Installing the same plugin twice on one app does nothing the second time, and Vue prints a warning in development.

flowchart LR
    A["createApp(App)"] --> B["app.use(plugin, options)"]
    B --> C["plugin.install(app, options)"]
    C --> D["app.component()"]
    C --> E["app.directive()"]
    C --> F["app.provide()"]
    C --> G["app.config.globalProperties"]
    D --> H["app.mount()"]
    E --> H
    F --> H
    G --> H

A plugin runs before mount and can use any of the four app-wide registration points.

What a plugin can do

Inside install you work with the app instance. These are the four common jobs:

  • app.component(name, component) registers a component for every template of the app, so you do not import it each time. Design-system plugins use this for their base buttons and inputs.
  • app.directive(name, directive) registers a custom directive globally.
  • app.provide(key, value) makes a value available to every component through inject (see provide and inject).
  • app.config.globalProperties.$name = value adds a property that every component template can use, such as $t. This is the app-wide version of putting a method on this in the Options API.

A plugin can also set app.config handlers, such as errorHandler, and add mixins, although mixins are discouraged in modern Vue.

A first plugin: translations

The classic example is internationalization (i18n). The plugin receives the available messages as an option, keeps the current locale in a ref, and exposes a translate function t.

There is one important detail. The translate function reads locale.value. Template expressions are tracked like any other reactive code, so when a template calls $t("greeting"), it depends on locale. Change the locale and every template that used $t renders again. That is why you do not need to do anything special to make the page update.

The plugin offers two ways in: $t in templates (a global property) and useI18n() in setup() (an injected value). The Symbol is the key for provide and inject, which avoids name clashes.

An i18n plugin with $t and useI18n

Switch between en, de and fr: the heading and the farewell change, and the picker, a separate component, highlights the active locale. The key missing.key has no message, so t falls back to showing the key itself. That is a deliberate convention, because a visible key is easier to spot during development than an empty string.

Two things to remember about global properties:

  • They are available in templates and through this in Options API components, but not inside <script setup>. There you use inject (the useI18n function above), which is why the plugin offers both.
  • If a component defines a property with the same name, the component's own property wins.

A second plugin: components, provide and options

The next plugin combines several of the registration points: it creates reactive state, registers a global component that displays it, provides an API through inject, and reads an option (max) with a default. It is a minimal toast (notification) system.

A toast plugin with a global component

Click Notify five times: only the last three notifications remain, because the plugin was installed with { max: 3 }. The Save button lives in a child component that gets the same toast API with inject, while the root template uses $toast. Both reach the same state, since the plugin created it once, inside install. Dismiss a toast with the small button.

Note where the state lives: inside install, so each app that installs the plugin gets its own independent toasts. That is the same reason Pinia keeps stores inside the application.

Packaging a set of components and directives

A plugin that only registers things is just as common. A team's design-system package often looks like this (read-only, because it needs a build step):

JavaScript
// design-system/index.js
import BaseButton from "./BaseButton.vue";
import BaseInput from "./BaseInput.vue";
import { vFocus } from "./directives.js";

export default {
  install(app) {
    app.component("BaseButton", BaseButton);
    app.component("BaseInput", BaseInput);
    app.directive("focus", vFocus);
  },
};
JavaScript
// main.js
import designSystem from "./design-system";

createApp(App).use(designSystem).mount("#app");

Every template in the app can now use <BaseButton> and v-focus without importing them.

Guidelines for writing plugins

  • Prefer provide/inject for new APIs. Injected values work in <script setup>, can be typed, and show clearly where they come from. Add a $name global property only when templates need a short helper.
  • Take options and give them defaults. Read options with a fallback (options.max ?? 3) so app.use(plugin) works without arguments.
  • Do not leak between apps. Create state inside install, not at the top of the module, unless you really want one shared instance (see simple stores).
  • Use clear names. Prefix global components and properties with something unique so two plugins cannot collide.
  • Export a useX() function next to the plugin, as the examples do, so components never need to know the injection key.

If you use TypeScript, tell it about your global property so templates are checked. This is a read-only declaration file:

TypeScript
// types.d.ts
export {};

declare module "vue" {
  interface ComponentCustomProperties {
    $t: (key: string, params?: Record<string, string>) => string;
  }
}

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Vue pass to a plugin's install function?

    install(app, options) receives the application instance and whatever you passed as the second argument of app.use().
  2. 2. Why does a template that calls $t('greeting') update when the plugin changes the locale ref?

    Template expressions are tracked like other reactive code. Reading locale.value inside t during render makes the component a subscriber, so it re-renders when the locale changes.
  3. 3. Why is inject the better way to expose an API to components that use <script setup>?

    Properties added with app.config.globalProperties are available in templates and through this in the Options API, but not as variables in <script setup>. inject works everywhere setup runs.
  4. 4. Where should a plugin create state that must be separate for each app that installs it?

    State created inside install belongs to that installation. State at the module's top level would be shared by every app that uses the plugin.

Summary

  • A plugin is an object with install(app, options) or a function with that signature, installed with app.use(plugin, options).
  • Inside install you can call app.component, app.directive, app.provide and add app.config.globalProperties.
  • Reactive state read during rendering (like locale.value) updates the templates that depend on it.
  • Prefer provide/inject plus a useX() function; global properties are only for templates and the Options API.
  • Create state inside install, accept options with defaults and name your registrations carefully.

Next: Render Functions and JSX