0
0
Vueframework~5 mins

Plugin installation and usage in Vue

Choose your learning style9 modes available
Introduction

Plugins add extra features to your Vue app easily. They help you reuse code and add tools without rewriting.

You want to add global features like a date picker or a UI library.
You need to share functions or data across many components.
You want to add third-party tools like routing or state management.
You want to add custom behavior to Vue app globally.
You want to keep your app code clean by using ready-made solutions.
Syntax
Vue
import { createApp } from 'vue'
import MyPlugin from 'my-plugin'

const app = createApp(App)
app.use(MyPlugin, { option1: true })
app.mount('#app')
Use app.use() to install a plugin before mounting the app.
You can pass options to customize the plugin behavior.
Examples
Installs a toast notification plugin with a 3-second timeout.
Vue
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')
Installs a custom plugin without options.
Vue
import { createApp } from 'vue'
import MyPlugin from './plugins/my-plugin.js'

const app = createApp(App)
app.use(MyPlugin)
app.mount('#app')
Installs a router plugin to manage app pages.
Vue
import { createApp } from 'vue'
import Router from './router'

const app = createApp(App)
app.use(Router)
app.mount('#app')
Sample Program

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.

Vue
/* 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>
OutputSuccess
Important Notes

Always install plugins before mounting the app.

Plugins can add global methods, directives, or components.

Check plugin docs for required options or setup steps.

Summary

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.