Skip to content

Vue Plugins

Plugins are tool code that can add global functionality to Vue. When we need to use certain features universally across the application, such as adding global methods, global components, global directives, or adding properties to the app instance, plugins are very useful.

A typical example is vue-router. When we execute app.use(router), we're actually installing the vue-router plugin. This plugin provides $router and $route properties for our application and registers the <router-link> and <router-view> global components.

Writing a Plugin

A plugin can be an object with an install() method, or it can directly be a function that will serve as the install() method. This install method receives the app instance as the first parameter, and options passed by the user as the second parameter.

Below is a simple plugin example that provides a global i18n (internationalization) translation function for all components.

src/plugins/i18n.js

js
export default {
  install: (app, options) => {
    // Plugin logic

    // 1. Add a global property on app.config.globalProperties
    // This way it can be accessed in any component's template via $translate
    app.config.globalProperties.$translate = (key) => {
      // Retrieve the translation from `options` via `key`
      // For example: options.greetings.hello
      return key.split('.').reduce((o, i) => {
        if (o) return o[i]
      }, options)
    }

    // 2. Provide a global injectable API
    // This way it can be accessed in any component's <script setup> via inject()
    app.provide('i18n', options)

    // 3. Register a global custom directive
    app.directive('my-directive', {
      /* ... */
    })

    // 4. Register a global component
    // app.component('MyComponent', MyComponent)
  }
}

Using Plugins

Plugins are installed through the app.use() method. It must be used before app.mount() is called.

src/main.js

js
import { createApp } from 'vue'
import App from './App.vue'
import i18nPlugin from './plugins/i18n'

const app = createApp(App)

// Plugin options
const i18nOptions = {
  greetings: {
    hello: '你好!',
    welcome: '欢迎!'
  }
}

// Install the plugin and pass options
app.use(i18nPlugin, i18nOptions)

app.mount('#app')

Now, we can use $translate in any component's template.

MyComponent.vue

vue
<script setup>
import { inject } from 'vue'

// Use inject to get the property provided by the plugin in <script setup>
const i18n = inject('i18n')
console.log(i18n.greetings.hello)
</script>

<template>
  <h1>{{ $translate('greetings.hello') }}</h1>
</template>

Plugins are a powerful and clean way to organize and distribute code that can be reused across the entire Vue application, avoiding polluting the global scope and maintaining logical encapsulation.

Content is for learning and research only.