Back
VueMediumNew
How do you create a plugin in Vue 3?
Object with an install method, or a function
Ideal Answer
A Vue plugin is an object with an install(app, options) method (or simply a function), used to add app-level functionality like global components, directives, or properties.
JavaScript
// myPlugin.js
export default {
install(app, options) {
app.config.globalProperties.$myMethod = () => { /* ... */ }
app.component('GlobalWidget', GlobalWidget)
app.directive('highlight', { mounted(el) { el.style.background = 'yellow' } })
}
}
// main.js
import { createApp } from 'vue'
import myPlugin from './myPlugin'
const app = createApp(App)
app.use(myPlugin, { someOption: true })