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
Using Plugins
Plugins are installed through the app.use() method. It must be used before app.mount() is called.
src/main.js
Now, we can use $translate in any component's template.
MyComponent.vue
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.