King Somto
16 Mar 2022
•
6 min read
Vue.Js is a frontend framework used to develop web apps and PWAs. This article has some requirements which include that you have some experience with using Vue Js and some of its internal features like Mixins that lets us access Vue lifecycle hooks.
A Vue.Js plugin is a collection of code or a code package that enables you to extend the functionality of Vue by adding global-level functionalities. Creating a plugin for Vue.js is quite easy.
Some popular examples of plugins made for Vue Js are:
Plugins allow you to reuse code/logic easily across multiple projects. Creating a VueJS plugin is not beyond your skills, it just requires a little effort and a certain structure to follow. Anyone familiar with how VueJS works can easily create a plugin.
Creating a plugin for Vue.Js requires that you have a module file that exports an object with the install method in it. This method takes 2 parameters:
Inside your project folder, create a new folder called plugins
inside the /src
folder.
You should now have a path like src/plugins
.
Create a javascript file named MyPlugin.js inside the src/plugins subfolder.
// src/plugins/MyPlugin.js
let MyPlugin = {
install(Vue) {
}
};
export default MyPlugin
The plugin needs to be imported so the VueJS app can make sure of it. One built-in feature of Vue Js is that if you were to import your plugin twice by mistake, normally this would cause problems with the functionality and make your project unnecessarily bigger but Vue Js makes sure that your plugin is imported only once.
// src/main.js
import Vue from "vue";
import App from "./App.vue";
import MyPlugin from "./plugins/MyPlugin.js";
Vue.use(MyPlugin);
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount(# app");
So far, we have not yet added any logic or real code to our plugin. Let's add that.
We would be logging a text to the console of our browser each time a new component is mounted with our plugin.
// src/plugins/MyPlugin.js
let MyPlugin = {
install(Vue) {
// create a mixin
Vue.mixin({
created() {
console.log("Hello from my Vue plugin");
},
});
},
};
export default MyPlugin
Now if you run your project and go to your browser, load your Dev Tools and check the console, you would see something like this:
Hello from my Vue plugin
Good job, you have created your first basic plugin.
Using the VueJs directive:
Let’s create a custom directive using the Vue. directive
// src/plugins/MyPlugin.js
let MyPlugin = {
install(Vue) {
//… Older code should be at the top
Vue.directive("highlight", {
inserted(el) {
el.style.color = "orange";
}
});
}
}
export default MyPlugin
Now inside the /src/App.vue
component, we would be able to use this directive like this:
// src/App.vue
<template>
<div id="app">
<p v-highlight>Hello, highlight this.</p>
</div>
</template>
<script>
export default {
name: "App"
};
</script>
If you go to your browser, you would see the text “Hello, highlight this.” in orange color. For further customization, we can pass some options when installing our plugin:
// src/main.js
import Vue from "vue";
import App from "./App.vue";
import MyPlugin from "./plugins/MyPlugin.js";
Vue.use(MyPlugin, { highlightColor: 'red' });
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount(# app");
Now we can receive the options object as the second parameter in the install function:
// src/plugins/MyPlugin.js
let MyPlugin = {
install(Vue, options) {
//… Older code should be at the top
Vue.directive("highlight", {
inserted(el) {
// use the plugin highlightColor if set or use "orange" as the default
el.style.color = options && options.highlightColor ? options.highlightColor : "orange";
}
});
}
}
export default MyPlugin
Congrats!
If you go to your browser, you will see the text Hello, highlight this.
in red
color now.
We are going to make a method that would be available globally using the VueJS prototype (instance property). This method would receive a string parameter called text
and would make it underlined using the underline HTML tag(<u> … </u>)
.
// src/plugins/MyPlugin.js
let MyPlugin = {
install(Vue, options) {
//… Older code should be at the top
Vue.prototype.$underline = function(text) {
return `<u>${text}</u>`;
};
}
};
export default MyPlugin
// src/App.vue
<template>
<div id="app">
<p v-html="$underline('this text should be underlined.')"></p>
</div>
</template>
<script>
export default {
name: "App"
};
</script>
When you open your browser, you will see a paragraph with the text underlined.
Congrats on your second plugin feature. 🎉 🎉 🎉
.
To avoid naming conflicts, instance properties in Vue are named with the $
prefix within the Vue community. This indicates that the property is a global one and not defined in the current component. Plugins that modify the Vue prototype are typically expected to prefix any added properties with a dollar sign ($)
.
In VueJs, we can create a global filter with the Vue. filter method. We would be creating a filter that capitalizes the first character of a string.
// src/plugins/MyPlugin.js
let MyPlugin = {
install(Vue, options) {
//… Older code should be at the top
Vue.filter('capitalize', function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})
}
}
export default MyPlugin
// src/App.vue
<template>
<div id="app">
<p>{{ message | capitalize}}</p>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
message: "hello world"
};
}
}
When you open your browser, you would see a paragraph with the text “Hello world”. The first character is capitalized. What is happening behind the hood is the text “hello world” is passed to the VueJs filter called capitalize as the parameter “value”. Inside the function, we cast the value to always be a string and then we get the first character in the value and make it uppercased. After that, we use the string slice method which extracts a section of a string and returns it as a new string, without modifying the original string.
Congrats on your third plugin feature. 🎉 🎉 🎉
Make sure you test the plugin properly to be sure that all the available features were implemented properly.
It is good practice that your code contains comments so other developers can understand it and you can remember how it works when you return to it in the future.
Since it's just you using the plugin, you might think that following best practice isn't necessary. But your plugin might grow over time, and other developers might be using it, or you might sell it.
You might come back to it in some year’s time and not be able to remember how the code is organized or works
Use good naming standards while writing your code
There are people who would use your plugin with Vue CDN for example or outside a module system(usually vue-CLI), for your plugin to be compatible with their project, you need to auto-install your plugin if it's called after the Vue script tag so they don't need to call the Vue.use()
method.
Use the following lines to implement this feature by appending these lines at the end of your plugin file (/src/MyPlugin.js)
.
// src/plugins/MyPlugin.js
//… Older code should be at the top
// Automatically install if Vue has been added to the global scope.
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(MyPlugin)
}
In the end, your final plugin code should look like this:
// src/plugins/MyPlugin.js
let MyPlugin = {
install(Vue, options) {
// create a mixin
Vue.mixin({
created() {
console.log("Hello from my Vue plugin");
}
});
Vue.directive("highlight", {
inserted(el) {
// use the plugin highlightColor if set or use "orange" as the default
el.style.color = options && options.highlightColor ? options.highlightColor : "orange";
}
});
Vue.prototype.$underline = function(text) {
return `<u>${text}</u>`;
};
Vue.filter("capitalize", function(value) {
if (!value) return "";
value = value.toString();
return value.charAt(0).toUpperCase() + value.slice(1);
});
}
};
// Automatically install if Vue has been added to the global scope.
if (typeof window !== "undefined" && window.Vue) {
window.Vue.use(MyPlugin);
}
export default MyPlugin;
Are you looking for some ideas you can implement as a plugin? Well, here are some that you can make some research on and implement into a plugin:
These are just some of what you can explore and create as a plugin for VueJS. You can also get more inspiration from NPM.
We have created an amazing sample plugin so far and you can see that it was easier than you thought. You finally made your first VueJS Plugin.
It requires practice to become proficient at developing complex VueJS plugins. As you become proficient at creating plugins, you'll be able to create a variety of them.
In this article, we hope to have provided you with a comprehensive overview of how to create your own VueJS plugin. You can also read more about how plugins work and how to create them from the official VueJS guide.
Good luck!
Photo by Steve Johnson from Pexels
Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ
108 E 16th Street, New York, NY 10003
Join over 111,000 others and get access to exclusive content, job opportunities and more!