DEV Community

Cover image for Writing a very simple plugin in Vue.js - (Example)
Nikos Koikas
Nikos Koikas

Posted on • Edited on

28 5

Writing a very simple plugin in Vue.js - (Example)

  • What is a Vue Plugin?
  • Writing and using a plugin

In this post, i will be showing you how you can write a basic plugin in Vue.
You should have a prior experience with Vue and JavaScript.

What is a Vue Plugin?

Enables you to add global-level functionality to Vue.
It's a good way to keep your Vue components clear and small. You can also package and share your code with other developers.
Specifically, plugin is nothing more than an object which expose an install method.

Writing and using a plugin

Firstly, you should export the plugin object, so it can be used anywhere in your project. Then expose the install method which takes two parameters: Vue constructor and options object. The second parameter - options - is optional and customize your plugin.
plugin.js

// plugin.js

// This exports the plugin object.
export default {
  // The install method will be called with the Vue constructor as
  // the first argument, along with possible options
  install (Vue, options) {
  }
}
Enter fullscreen mode Exit fullscreen mode

But a question which arises is where do I provide these options?

OK. You can call use() method and pass yourPlugin and your options as arguments, since you have already imported your plugin.js into main.js file.

main.js

// main.js

import Vue from 'vue'
import yourPlugin from './plugin.js'

// Without options
Vue.use(yourPlugin)
// With options
Vue.use(yourPlugin, {
    someOption: true
})

new Vue({
  el: '#app',
  render: h => h(App)
})
Enter fullscreen mode Exit fullscreen mode

Install method - Plugins
The install method contains one or more of the following:

  • Add some global methods or properties.
  • Add one or more global assets: directives/filters/transitions etc.
  • Add some component options by global mixin.

Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.

  • Add some Vue instance methods by attaching them to Vue.prototype.
// plugin.js
import Component from '/src/components/Component.vue'

// This exports the plugin object.
export default {
  // The install method will be called with the Vue constructor as         
  // the first argument, along with possible options
  install (Vue, options) {
     // Add or modify global methods or properties.
     Vue.yourMethod = (value) => value
     // Add a component or directive to your plugin, so it will be installed globally to your project.
     Vue.component('component', Component)
     // Add `Vue.mixin()` to inject options to all components.
     Vue.mixin({
         // Add component lifecycle hooks or properties.
         created() {
            console.log('Hello from created hook!')
         }
     })
     // Add Vue instance methods by attaching them to Vue.prototype.
     Vue.prototype.$myProperty = 'This is a Vue instance property.'
  }
}
Enter fullscreen mode Exit fullscreen mode

Now, let's take a deep dive into our example's code

-------- EXAMPLE ---

<template>
<div id="app">
{{ $myInfo('George', 37) }}
<!-- My name is George and I am a 37 years old Web Dev. -->
</div>
</template>
<script>
export default {
name: 'App',
created() {
console.log(this.$surname) // Smith
this.$surname = 'Blacksmith'
console.log(this.$surname) // Blacksmith
}
}
</script>
view raw App.vue hosted with ❤ by GitHub
import Vue from 'vue'
import App from './App'
import myPlugin from './plugin.js'
Vue.use(myPlugin, {
job: 'Web Dev'
})
new Vue({
el: '#app',
render: h => h(App)
})
view raw main.js hosted with ❤ by GitHub
export default {
// The install method will be called with the Vue constructor as the first argument, along with possible options
install (Vue, options) {
// ES6 way of const job = options.job
const { job } = options
// Add $plugin instance method directly to Vue components
Vue.prototype.$myInfo = (name, age) => info(name, age, job)
// Add $surname instance property directly to Vue components
Vue.prototype.$surname = 'Smith'
}
}
// info method returns a string with name, age and job (with default values)
const info = (name = 'John', age = 22, job = 'student') => `My name is ${name} and I am a ${age} years old ${job}.`
view raw plugin.js hosted with ❤ by GitHub

Distributing

So you have built your first plugin in Vue. It's time to distribute it to the community - if you want.

  • Upload the source files to Github and then
  • Publish the package to NPM.

Until next time...Happy coding!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (7)

Collapse
 
asgouros profile image
asgouros

Vue.property.$myProperty there is an error there, should be Vue.prototype.$myProperty

Collapse
 
michealjroberts_57 profile image

Although I 100% like and use this method - it does throw an ESLint error:

error: Assignment to property of function parameter 'Vue' (no-param-reassign) at src/plugins/plugin.js:5:5:

Collapse
 
michaelgitart profile image
Michael

Thanks, realy great guide!

Collapse
 
dylajwright profile image
Dylan

This is a great simple guide, pairing it with unit tests would be even better almost perfect.

Collapse
 
yavuztas profile image
Yavuz Tas

Thank you for your explanation. It helped me a lot!

Collapse
 
nekooee profile image
nekooee

how can I publish it in npm???

Collapse
 
nirnejak profile image
Jitendra Nirnejak

Great article, I would also recommend checking out this article about the same
inkoop.io/blog/building-custom-plu...

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • --last-failed: Zero in on just the tests that failed in your previous run
  • --only-changed: Test only the spec files you've modified in git
  • --repeat-each: Run tests multiple times to catch flaky behavior before it reaches production
  • --forbid-only: Prevent accidental test.only commits from breaking your CI pipeline
  • --ui --headed --workers 1: Debug visually with browser windows and sequential test execution

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Practical examples included!

Watch Video 📹️

👋 Kindness is contagious

DEV shines when you're signed in, unlocking a customized experience with features like dark mode!

Okay