Vue3 Plugins
About 187 wordsLess than 1 minute
Vue3Plugins
2025-01-20
What is a Vue Plugin
A Vue plugin is an object or function that must provide an install method (when it is a function, the function itself will be used as the install method). The install method is executed when app.use() is called.
// MyPlugin.js
export default {
install(app, options) {
// Add global method
app.config.globalProperties.$myMethod = () => {
console.log('This is a global method');
};
// Register global component
app.component('MyComponent', {
template: `<div>A global component</div>`,
});
// Add global directive
app.directive('focus', {
mounted(el) {
el.focus();
},
});
//
const authService = {
login: () => console.log('Logging in...'),
};
// Provide service to components through provide
app.provide('auth', authService);
// Configure plugin behavior through options
console.log('Plugin options:', options);
},
};
// Using the plugin in main.js
import { createApp } from 'vue';
import App from './App.vue';
import MyPlugin from './MyPlugin';
const app = createApp(App);
// Use the plugin and pass options
app.use(MyPlugin, { key: 'value' });
app.mount('#app');
// In a component
import { inject } from 'vue';
const auth = inject('auth');
auth.login();
Common Vue Plugins
- Vue Router
- Pinia
- Vue i18n
- Vue Apollo