Tutorial

How To Create Custom Vue.js Plugins

Updated on July 29, 2021
author

Joshua Bemenderfer

How To Create Custom Vue.js Plugins

Introduction

Vue.js plugins are a powerful but simple way to add global features to your app. They have a variety of uses, from distributing app-wide components to adding additional capabilities such as routing and immutable data stores to your app.

In this article, you will build an example Vue custom plugin.

Prerequisites

To follow along with this article, you will need:

This tutorial was verified with Node v16.5.0, npm v6.14.8, and vue v2.6.11.

Building Your First Plugin

As an introduction to the world of Vue plugins, we’re going to write a plugin that writes to the console every time a component is mounted to the DOM.

my-vue-plugin.js
const MyPlugin = {
  // eslint-disable-next-line no-unused-vars
  install(Vue, options) {
    Vue.mixin({
      mounted() {
        console.log('Mounted!');
      }
    });
  }
};

export default MyPlugin;

A Vue plugin is an object with an install method that takes two parameters:

  • the global Vue object
  • and an object containing user-defined options

Vue.mixin() is used to inject functionality into all components. In this case, the mounted() method runs when the component is added to the DOM.

Your plugin can now be used in a Vue app by importing it and calling Vue.use(MyPlugin):

main.js
import Vue from 'vue'
import MyPlugin from './my-vue-plugin.js'
import App from './App.vue'

Vue.use(MyPlugin)

new Vue({
  el: '#app',
  render: h => h(App)
});

You might be wondering, why couldn’t I just do this by calling Vue.mixin() in main.js? The reason is that since we’re adding global functionality to Vue that does not modify the app directly, it’s almost always best to split that out into a separate module that can be added or removed at will. It also makes plugins incredibly easy to distribute.

Adding Capabilities

Adding Component Lifecycle Hooks or Properties

As depicted above in the “Your First Plugin” example, you can add lifecycle hooks and make other modifications to Vue components by using a Mixin.

Note: Mixins are a fairly advanced topic that is outside the scope of this article. For now, a sufficient explanation is that they’re essentially component definitions that get combined into (“mixed in”) other components.

my-vue-plugin.js
const MyPlugin = {
  // eslint-disable-next-line no-unused-vars
  install(Vue, options) {
    Vue.mixin({
      mounted() {
        console.log('Mounted!');
      }
    });
  }
};

export default MyPlugin;

Installing App-Wide Components and Directives

If you wish to package components or directives to be distributed as a plugin, you might write something like this:

my-vue-plugin.js
import MyComponent from './components/MyComponent.vue'
import MyDirective from './directives/MyDirective.js'

const MyPlugin {
  // eslint-disable-next-line no-unused-vars
  install(Vue, options) {
    Vue.component(MyComponent.name, MyComponent)
    Vue.directive(MyDirective.name, MyDirective)
  }
};

export default MyPlugin;

Modifying the Global Vue Object

You can modify the global Vue object from a plugin:

my-vue-plugin.js
const MyPlugin {
  // eslint-disable-next-line no-unused-vars
  install(Vue, options) {
    Vue.myAddedMethod = function() {
      return Vue.myAddedProperty
    }
  }
};

export default MyPlugin;

Modifying Vue Instances

To add a property or method directly to component instances without any injection mechanism, you can modify the Vue prototype as shown here:

my-vue-plugin.js
const MyPlugin {
  // eslint-disable-next-line no-unused-vars
  install(Vue, options) {
    Vue.prototype.$myAddedProperty = 'Example Property'
    Vue.prototype.$myAddedMethod = function() {
      return this.$myAddedProperty
    }
  }
};

export default MyPlugin;

Those properties will now be added to all components and Vue instances.

Note: Within the Vue community, it is generally expected that plugins that modify the Vue prototype prefix any added properties with a dollar sign ($).

Supporting Automatic Installation

For people who use your plugin outside of a module system, it is often expected that if your plugin is included after the Vue script tag, that it will automatically install itself without the need to call Vue.use(). You can implement this by appending these lines to the end of my-vue-plugin.js:

if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(MyPlugin)
}

Automatic installation if Vue has been added to the global scope.

Distributing Your Plugin

Once you’ve written a plugin, you can distribute it to the community. If you’re not already familiar with the process, here are some common steps for helping people discover your plugin:

  1. Publish the source code and distributable files to npm and GitHub. Make sure you choose a fitting license for your code!
  2. Open a pull request to the official Vue cool-stuff-discovery repository: awesome-vue. Lots of people come here to look for plugins.
  3. (Optional) Post about it on the Vue Forum, Vue Gitter Channel and on Twitter with the hashtag #vuejs.

Go make some plugins!

Conclusion

In this article, you built an example Vue custom plugin.

Continue your learning with Vue documentation for Plugins and Mixins.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Joshua Bemenderfer

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.