We're planting a tree for every job application! Click here to learn more

How to create a VueJS Plugin

King Somto

16 Mar 2022

•

6 min read

How to create a VueJS Plugin
  • JavaScript

Requirements

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.

What is a Vue.js Plugin?

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:

  • Vue-router
  • Vue-touch
  • Vuedraggable
  • Vue-infinite-loading
  • Etc

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.

How to 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:

  • The Vue constructor instance object
  • An object of options

Step 1: Create a plugin folder

Inside your project folder, create a new folder called plugins inside the /src folder. You should now have a path like src/plugins.

Step 2: Create the VueJS plugin file and import it

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.

Step 3: Add basic logic to the plugin

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.

Step 4: Make the plugin useful

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.

Adding a method to VueJs:

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. 🎉 🎉 🎉.

Note on naming conventions:

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 ($).

Creating a global VueJS Filter

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. 🎉 🎉 🎉

Good practices for VueJs plugin creation

  • 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

Plugin Automatic Installation

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)
}

Your final plugin code:

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;

Some VueJs plugin ideas:

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:

  • An encrypted browser local storage plugin
  • A user browser detection plugin
  • An error logging plugin
  • A PDF viewer plugin
  • A currency formatting plugin
  • A currency converter plugin
  • Form validation plugin
  • Display a User Gravatar from an Email Address plugin
  • A Twitter feed to site embed plugin
  • An Email obfuscator plugin
  • An RSS reader plugin
  • Social media accounts links plugin
  • A JSON/TSV to CSV/Excel file generator plugin
  • A long text truncating plugin
  • A social media link sharing plugin
  • An RSS generator plugin
  • Etc

These are just some of what you can explore and create as a plugin for VueJS. You can also get more inspiration from NPM.

Conclusion

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

Did you like this article?

King Somto

Dev

See other articles by King

Related jobs

See all

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Related articles

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

•

12 Sep 2021

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

•

12 Sep 2021

WorksHub

CareersCompaniesSitemapFunctional WorksBlockchain WorksJavaScript WorksAI WorksGolang WorksJava WorksPython WorksRemote Works
hello@works-hub.com

Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ

108 E 16th Street, New York, NY 10003

Subscribe to our newsletter

Join over 111,000 others and get access to exclusive content, job opportunities and more!

© 2024 WorksHub

Privacy PolicyDeveloped by WorksHub