#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 27 of 37hard

How to create Vue Plugins?

Extending Vue with plugins.

What You'll Learn

  • Plugin structure
  • Installing plugins
  • Plugin options

Plugin Structure

code.jsJavaScript
// my-plugin.js
export default {
  install(app, options) {
    // Add global method
    app.config.globalProperties.$myMethod = () => {}

    // Add global directive
    app.directive('my-directive', {})

    // Add global component
    app.component('MyComponent', {})

    // Provide global value
    app.provide('myKey', options.someValue)
  }
}

Installing Plugins

code.jsJavaScript
// main.js
import { createApp } from 'vue'
import MyPlugin from './my-plugin'

const app = createApp(App)
app.use(MyPlugin, { someValue: 'hello' })
app.mount('#app')

Practical Plugin Example

code.jsJavaScript
// toast-plugin.js
export default {
  install(app) {
    const toast = {
      show(message) {
        // Show toast logic
      }
    }

    app.config.globalProperties.$toast = toast
    app.provide('toast', toast)
  }
}

// Usage in component
const toast = inject('toast')
toast.show('Hello!')