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:
// plugins/i18n.js
export default {
install: (app, options) => {
app.config.globalProperties.$translate = (key) => {
return key.split('.').reduce((o, i) => (o ? o[i] : null), options);
};
},
};This plugin exposes a $translate function that looks up translated strings using a dot-delimited key.
Install the plugin and provide translation options:
import i18nPlugin from './plugins/i18n';
app.use(i18nPlugin, {
greetings: {
hello: 'Bonjour!',
},
});Now, you can use $translate in your templates:
<template>
<h1>{{ $translate('greetings.hello') }}</h1>
</template>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:
// plugins/i18n.js
export default {
install(app, options) {
app.provide('i18n', options);
},
};Plugin users can inject the options into their components:
<script setup>
import { inject } from 'vue';
const i18n = inject('i18n');
console.log(i18n.greetings.hello);
</script>Note: Use global properties sparingly to avoid confusion when multiple plugins inject global properties.
Last updated