A Step-By-Step Guide to Building Your First VueJS Plugin

Matt Maribojoc
Jan 7 · 7 min read
Image for post
Image for post
Photo by Max Duzij on Unsplash

As VueJS grows in popularity, community-created VueJS plugins are becoming more common and more powerful.

In fact, there are some plugins that I find insanely useful. For example, there are amazing UI libraries and utility plugins that have saved me tons of time in development.

While creating your own plugin may seem like an overwhelming task, it’s actually a lot more doable than you think. By the end of this tutorial, you will have…

  • Created your first VueJS plugin
  • An overview how they work
  • Learned all the tools to build more complicated plugins

Time to dive right in!!

How to Setup Your Plugin

  1. The Vue constructor
  2. An object of options

Let’s make it.

In our Vue project, create a new folder at src/plugins.

Then in our new folder, we can actually create our plugin file. For this tutorial, I named it first-plugin.js

Inside our new plugin file, we should just follow a typical ES6 module pattern AKA the whole “export default” thing. Export Default allows us to export our plugin from its file and allow other files to import it.

Next, like we were discussing earlier, our plugin must expose a .install(Vue, options) method. This is what Vue actually calls when we install our plugin.

So right now, the skeleton code should look a little like this.

export default {
// called by Vue.use(FirstPlugin)
install(Vue, options) {

}
}

Now, let’s actually add some stuff to this code.

Adding Functionality to a Plugin

Building Your First Plugin

If you’re unfamiliar, this is a basic overview of VueJS mixins. Essentially, they allow you to inject additional component options. They’re a great way to extract and reuse common functionality between components. Mixins also allow your plugin to access Vue lifecycle hooks.

To add a mixin to a plugin, we declare our additional component options inside the Vue.mixin function. To get started, I just added a created lifecycle hook with a console.log statement.

Our plugin code should now look like this.

export default {
// called by Vue.use(FirstPlugin)
install(Vue, options) {

// create a mixin
Vue.mixin({
created() {
console.log(Vue);
}
});
}
}

Installing Your Plugin

Thankfully, this is a super easy two line process. In our src/main.js file — the file that declares our Vue constructor — we just have to import and install our plugin file.

This is done with these lines of code.

import FirstPlugin from "./plugins/first-plugin.js"; Vue.use(FirstPlugin);

One great thing about Vue.use is that it makes sure that your plugin is only installed once. If you were to somehow accidentally add it twice, it would slow down your app and probably mess up some functionality. Thankfully, the Vue developers provided this safety net.

Finally. We have our plugin installed. Now, if we run our project and check out the logs we should see some output in the console.

Image for post
Image for post

Let’s Make It Actually Useful

Let’s go over some neat ways to make your plugins functional.

Declaring Global Properties

install(Vue, options) {
// define a global property
Vue.VERSION = 'v2.0.3';
}

One thing to watch out for is overusing globals. It’s super easy to overcrowd the global scope and make it a pain to use.

Defining Instance Properties

In this example, I just created an instance method that takes a string and places inside <i> tags.

Note: the $ is not necessary syntax; it’s just the naming convention that Vue uses for instance properties to avoid conflicts.

// define an instance method
Vue.prototype.$italicHTML = function (text) {
return '<i>' + text + '</i>';
}

Then, we can use it inside any Vue instance like this…

<div v-html='$italicHTML(content)'>
</div>

Building a Global Filter

Using an example from my previous tutorial on filters, let’s say we want to use a filter to generate preview snippet from a longer text. We would want to do something like this in our plugin.

// define a global filter
Vue.filter('preview', (value) => {
if (!value) {
return '';
}
return value.substring(0, userOptions.cutoff) + '...';
})

Adding Custom Directives

Looking at the example from the VueJS docs, let’s create a custom directive inside our plugin that automatically focuses an element on a page.

Inside the install method, we just have to use the Vue.directive method to declare our new directive.

// add a custom directive
Vue.directive('focus', {
// When the bound element is inserted into the DOM...
inserted: function (el) {
// Focus the element
el.focus();
}
})

Then, we can just add it onto an element. This is how we would automatically focus a text input on page load.

<input type='text' placeholder='Type...' v-focus />

Incorporating the Options Object

In order to use the options object, we first have to pass our plugin some options.

One best practice when working with the options object is to create some default values. We can do this by defining our default options object privately to the plugin file and then using Javascript’s spread syntax to merge our default options with the argument options.

Looking back at our previous example, let’s say that we want to add an option that allows us to set the cutoff point of the text preview. That would go something like this…

const defaultOptions = {
cutoff: 50
};

export default {
// called by Vue.use(FirstPlugin)
install(Vue, options) {

// merge default options with arg options
let userOptions = {...defaultOptions, ...options};

// REST OF PLUGIN CODE
}
}

Now, even if there is no options passed to the plugin, it will still run with the default values.

If we did want to pass options, it’s simple. Inside our src/main.js file, all we have to do is add a second argument to our Vue.use method. This argument will be an options object.

Vue.use(FirstPlugin, { cutoff: 100 });

Because we put our argument options on the right side of the spread syntax, it overwrites our defaults.

Our Final Hodge-Podge Plugin

const defaultOptions = {
cutoff: 50
};

export default {
// called by Vue.use(FirstPlugin)
install(Vue, options) {

// merge default options with arg options
let userOptions = {...defaultOptions, ...options};

// create a mixin
Vue.mixin({
created() {
console.log(Vue);
}
});

// define a global property
Vue.VERSION = 'v2.0.3';

// define an instance method
Vue.prototype.$italicHTML = function (text) {
return '<i>' + text + '</i>';
}

// define a global filter
Vue.filter('preview', (value) => {
if (!value) {
return '';
}
return value.substring(0, userOptions.cutoff) + '...';
})

// add a custom directive
Vue.directive('focus', {
// When the bound element is inserted into the DOM...
inserted: function (el) {
// Focus the element
el.focus();
}
})
}
}

Yes. This plugin is definitely all over the place in terms of functionality. But, if you followed along, you are now familiar with most of the tools, methods, and techniques you need to build more advanced plugins.

Conclusion

I’d love to see the plugins you create or what your favorite plugins are in general. Just mention us on Twitter @learnvueco or post on our Facebook group 🙂


If you’re looking to power up your Vue development, I’ve created a 3 page PDF cheatsheet with all of the essential references that every Vue developer needs. It’s saved me so much time and thousands of the same Google searches.

Image for post
Image for post

Originally published at https://learnvue.co on January 7, 2020.

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store