0 day streak
javascript / intermediate
Snippet

Developing a Vue Plugin with Global Methods

Plugins are self-contained code that adds app-level functionality to Vue. Using the 'install' method, you can add global properties, directives, or provide dependencies that are accessible throughout the entire application via the Composition API.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// myPlugin.js
export default {
install: (app, options) => {
app.config.globalProperties.$translate = (key) => {
return key.split('.').reduce((o, i) => o[i], options.messages);
};
app.provide('i18n', options);
}
};
// main.js
import myPlugin from './myPlugin';
app.use(myPlugin, { messages: { greeting: 'Hello' } });
vue
Breakdown
1
install: (app, options) => {
The mandatory entry point for any Vue plugin.
2
app.config.globalProperties
Adds a property accessible in any component instance via 'this'.
3
app.provide('i18n', options);
Makes data available for injection into any child component.