0
0
Vueframework~5 mins

Plugin creation basics in Vue

Choose your learning style9 modes available
Introduction

Plugins help add reusable features to your Vue app easily. They let you share code across many components.

You want to add a global function or property accessible in all components.
You need to register global components or directives once for the whole app.
You want to add third-party libraries with a simple setup.
You want to share common logic or utilities across many parts of your app.
Syntax
Vue
export default {
  install(app, options) {
    // Add global properties, components, or directives here
    app.config.globalProperties.$myMethod = () => {
      console.log('Hello from plugin!')
    }
  }
}

The install method is called by Vue when you use app.use().

The app argument is the Vue application instance.

Examples
This plugin adds a global greeting method you can call in any component.
Vue
export default {
  install(app) {
    app.config.globalProperties.$greet = (name) => `Hi, ${name}!`
  }
}
This plugin globally registers a simple button component.
Vue
export default {
  install(app) {
    app.component('MyButton', {
      template: `<button><slot /></button>`
    })
  }
}
Sample Program

This example creates a Vue app and uses a plugin that adds a global method $sayHello. The app shows the message from this method.

Vue
import { createApp } from 'vue'

const MyPlugin = {
  install(app) {
    app.config.globalProperties.$sayHello = () => 'Hello from plugin!'
  }
}

const app = createApp({
  template: `<div>{{ message }}</div>`,
  computed: {
    message() {
      return this.$sayHello()
    }
  }
})

app.use(MyPlugin)
app.mount('#app')
OutputSuccess
Important Notes

Always call app.use() before mounting the app.

Global properties added by plugins are accessible in all components via this.

Plugins can accept options by adding a second parameter to install(app, options).

Summary

Plugins add reusable features globally to your Vue app.

Define an install method to add properties, components, or directives.

Use app.use() to activate the plugin before mounting.