Vue Plugins
Introduction
Vue plugins are self-contained pieces of code that add functionality to your Vue application. To use a plugin, you employ the app.use() method in your Vue application:
import { createApp } from 'vue';
const app = createApp({});
app.use(myPlugin, {
/* optional options */
});A plugin can be an object with an install() method or simply a function acting as the install function. The install function receives the app instance and additional options passed to app.use().
const myPlugin = {
install(app, options) {
// Configure the app
},
};Common use cases for plugins include registering global components, custom directives, making resources injectable throughout the app, and adding global instance properties or methods.
Writing a Plugin
Let's create a simplified i18n (Internationalization) plugin that provides a global translation function. Create a separate file for the plugin:
This plugin exposes a $translate function that looks up translated strings using a dot-delimited key.
Install the plugin and provide translation options:
Now, you can use $translate in your templates:
Provide / Inject with Plugins
Plugins also allow providing a function or attribute to the plugin's users. For example, providing access to the translation options:
Plugin users can inject the options into their components:
Note: Use global properties sparingly to avoid confusion when multiple plugins inject global properties.
Last updated