Sandocs

Writing a Plugin

A plugin is defined as either an object that exposes an install() method, or simply a function that acts as the install function itself. The install function receives the app instance along with additional options passed to app.use(), if any:

const myPlugin = {
  install(app, options) {
    // configure the app
  }
}

There is no strictly defined scope for a plugin, but common scenarios where plugins are useful include

Register one or more global components or custom directives with app.component() and app.directive().

A library that needs to perform some combination of the above.

Writing a Plugin #

In order to better understand how to create your own plugins, we will create a very simplified version of a plugin that displays i18n (short for Internationalization) strings.

Let's begin by setting up the plugin object. It is recommended to create it in a separate file and export it, as shown below to keep the logic contained and separate.

// plugins/i18n.js
export default {
  install: (app, options) => {
    // inject a globally available $translate() method
    app.config.globalProperties.$translate = (key) => {
      // retrieve a nested property in `options`
      // using `key` as the path
      return key.split('.').reduce((o, i) => {
        if (o) return o[i]
      }, options)
    }
  }
}

We want to make a function to translate keys available to the whole application, so we will expose it using app.config.globalProperties. This function will receive a dot-delimited key string, which we will use to look up the translated string in the user-provided options.

import i18nPlugin from './plugins/i18n'

app.use(i18nPlugin, {
  greetings: {
    hello: 'Bonjour!'
  }
})

The plugin expects users to pass in an object containing the translated keys via the options when they use the plugin.

Our $translate function will take a string such as greetings.hello, look inside the user provided configuration and return the translated value - in this case, Bonjour!:

Provide / Inject with Plugins #

Plugins also allow us to use inject to provide a function or attribute to the plugin's users. For example, we can allow the application to have access to the options parameter to be able to use the translations object.

Plugin users will now be able to inject the plugin options into their components using the i18n key.