Skip to content

What Is a Vue Plugin?

A Vue plugin is a set of features or functionality designed for Vue applications. Plugins are usually used to extend Vue's core abilities, add reusable components or directives, or make applications more modular and flexible.

Vue plugins can include:

  1. Global methods or properties: a plugin can add global methods or properties that every component can use.
  2. Custom directives: directives give more control over the DOM; plugins can add them to provide custom behaviour or interaction.
  3. Filters: in Vue 2, filters format data; plugins could add new ones.
  4. Components: reusable components or whole UI kits can be added to an application through plugins.
  5. Mixins: plugins can provide global mixins to add shared behaviour to every component.
  6. Application options: some plugins add configuration or functionality when the application starts.

Plugins are installed with the use() method, which integrates them into the application and can apply settings at start-up. A router or a state management library, for example, is added to a Vue application this way.

Below is a simple plugin written for Vue 3. It adds a $formatPrice helper method and a v-focus directive to every component:

JavaScript
import { createApp } from 'vue';

const pricePlugin = {
  install(app, options) {
    // A global method available in every component
    app.config.globalProperties.$formatPrice = (value) =>
      new Intl.NumberFormat('en-GB', {
        style: 'currency',
        currency: options.currency,
      }).format(value);

    // A global directive: focuses the element when it appears
    app.directive('focus', { mounted: (element) => element.focus() });
  },
};

const app = createApp({
  template: `
    <p>Price: {{ $formatPrice(1499.9) }}</p>
    <input v-focus placeholder="Focused automatically" />
  `,
});

app.use(pricePlugin, { currency: 'EUR' });
app.mount('#app');

Note (Vue 3): In Vue 3, plugins are installed on the application instance with app.use() instead of Vue.use(), and global properties are added with app.config.globalProperties instead of Vue.prototype. Filters were removed in Vue 3; use methods or computed properties instead.

Have a question about this article? Write to me