Introduction
Plugins add extra features to your Vue app easily. They help you reuse code and add tools without rewriting.
Plugins add extra features to your Vue app easily. They help you reuse code and add tools without rewriting.
import { createApp } from 'vue' import MyPlugin from 'my-plugin' const app = createApp(App) app.use(MyPlugin, { option1: true }) app.mount('#app')
app.use() to install a plugin before mounting the app.import { createApp } from 'vue' import ToastPlugin from 'vue-toastification' import 'vue-toastification/dist/index.css' const app = createApp(App) app.use(ToastPlugin, { timeout: 3000 }) app.mount('#app')
import { createApp } from 'vue' import MyPlugin from './plugins/my-plugin.js' const app = createApp(App) app.use(MyPlugin) app.mount('#app')
import { createApp } from 'vue' import Router from './router' const app = createApp(App) app.use(Router) app.mount('#app')
This example shows a simple logger plugin that adds a $log method globally. When you click the button, it logs a message to the console if logging is enabled.
/* plugins/logger.js */ export default { install(app, options) { app.config.globalProperties.$log = (msg) => { if (options?.enabled) { console.log(`LOG: ${msg}`) } } } } /* main.js */ import { createApp } from 'vue' import App from './App.vue' import LoggerPlugin from './plugins/logger.js' const app = createApp(App) app.use(LoggerPlugin, { enabled: true }) app.mount('#app') /* App.vue */ <template> <button @click="sayHello">Click me</button> </template> <script setup> import { getCurrentInstance } from 'vue' const { proxy } = getCurrentInstance() function sayHello() { proxy.$log('Hello from plugin!') } </script>
Always install plugins before mounting the app.
Plugins can add global methods, directives, or components.
Check plugin docs for required options or setup steps.
Plugins add reusable features to Vue apps easily.
Use app.use() to install plugins with optional settings.
Plugins can add global properties, components, or behaviors.
MyPlugin in a Vue 3 app?app.use() with the plugin.const MyPlugin = {
install(app, options) {
app.config.globalProperties.$greet = () => `Hello, ${options.name}!`;
}
};
const app = Vue.createApp({});
app.use(MyPlugin, { name: 'Alice' });
app.mount('#app');
// In a component template: {{ $greet() }}const app = Vue.createApp({});
app.mount('#app');
app.use(MyPlugin);app.mount() to ensure plugin features are available.MyButton and adds a global method $log to log messages. Which is the correct way to write the plugin's install method?app.component() to register components and app.config.globalProperties to add global methods.Pass the test and this pattern moves unknown