n How to create custom plugin in Vue.js | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

Creating a new Vue plugin is simple. We just have to create a module that exports an object with the install method inside it.

The install method has a Vue parameter for the Vue instance, and an options object that takes various options that we pass in by calling Vue.use to register the plugin.

With with steps above, we can build our own plugin. We can add a mixin with the Vue.mixin function.

Mixins let us access Vue lifecycle hooks.

Also, we can add properties to Vue.prototype to add methods to our components.

To create a bare-bones plugin, we can write the following:

plugin.js

export default {
  install(Vue, options) {
    Vue.mixin({
      created() {
        console.log("hello");
      }
    });
  }
};

main.js

import Vue from "vue";
import App from "./App.vue";
import plugin from "./plugin";

Vue.config.productionTip = false;

Vue.use(plugin);

new Vue({
  render: h => h(App)
}).$mount("#app");

In plugin.js , we exported an object with a default export that has the install method inside, which has the Vue parameter with the Vue instance and options with options, we pass into a Vue object.

We called Vue.mixin with the created method to modify the created hook globally so that whatever we have inside will be called when any component is initialized and the created hook is called.

Since we have console.log('hello') inside the mixin, that’ll be called when our component loads.

In main.js , we registered our plugin globally by calling Vue.use with the plugin we imported as the argument.

We’ll see 'hello' logged in the console log output.

To accept options with our plugin, we can pass them into Vue.use and use it our plugin as follows:

plugin.js

export default {
  install(Vue, options) {
    Vue.mixin({
      created() {
        const { greeting } = options;
        console.log(greeting);
      }
    });
  }
};

main.js

import Vue from "vue";
import App from "./App.vue";
import plugin from "./plugin";

Vue.config.productionTip = false;
Vue.use(plugin, { greeting: "hello world" });
new Vue({
  render: h => h(App)
}).$mount("#app");

In the code above, we get the greeting property from the options parameter. Then since we passed in an object with the greeting property as the 2nd argument of the Vue.use , we’ll see 'hello world' from the console log output.

 

Instance Properties

We can add our own instance properties to our plugin by adding properties to the Vue.prototype object.

The properties that we add should start with a $ symbol to distinguish them from properties that we define in our components.

For instance, we can add our own properties as follows:

plugin.js

export default {
  install(Vue, options) {
    Vue.prototype.$bold = text => {
      return `<b>${text}</b>`;
    };
  }
};

App.vue

<template>
  <div id="app" v-html="greeting"></div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      greeting: "hello"
    };
  },
  beforeMount() {
    this.greeting = this.$bold(this.greeting);
  }
};
</script>

In the code above, we have the following method in the install method:

Vue.prototype.$bold = text => {
  return `<b>${text}</b>`;
};

which can be called within our component since it’s part of the Vue prototype.

Then in App.vue , we can call it as follows:

this.greeting = this.$bold(this.greeting);

and then we can set the text by using the v-html directive as follows in App.vue :

<div id="app" v-html="greeting"></div>

Then we see the text shown on the screen.

 

Global Filters

We can add a global filter with the Vue.filter method.

The filter method takes a string with the filter name as the first argument and the function which takes an input and value and returns the value formatted as we like as the 2nd argument.

For instance, we can write the following code to do that:

plugin.js

export default {
  install(Vue, options) {
    Vue.filter("localeDateString", value => {
      if (!(value instanceof Date)) {
        return value;
      }
      return value.toLocaleDateString();
    });
  }
};

In the code above, we have the localeDateString filter, which returns the date string generated from a date object.

Then in App.vue , we can use it as follows:

<template>
  <div id="app">{{new Date() | localeDateString}}</div>
</template>

<script>
export default {
  name: "App"
};
</script>

And we get the locale-dependent date string displayed instead of the default date string.

 

Custom Directives

We can call the Vue.directive method to add a directive in our plugin.

The method takes a directive name string as the first argument and the directive object as the 2nd argument.

For instance, we can use it as follows:

plugin.js

export default {
  install(Vue, options) {
    Vue.directive("highlight", {
      inserted(el) {
        el.style.color = "red";
      }
    });
  }
};

In the code above, we have a highlight directive that changes the element’s content to the color red when we bind the directive to it.

Then when we use it as follows:

<template>
  <div id="app" v-highlight>foo</div>
</template>

<script>
export default {
  name: "App"
};
</script>

We get that ‘foo’ is red.

 

Example:

A Vue.js plugin should expose an install method. The method will be called with the Vue constructor as the first argument, along with possible options:

MyPlugin.install = function (Vue, options) {
  // 1. add global method or property
  Vue.myGlobalMethod = function () {
    // some logic ...
  }

  // 2. add a global asset
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // some logic ...
    }
    ...
  })

  // 3. inject some component options
  Vue.mixin({
    created: function () {
      // some logic ...
    }
    ...
  })

  // 4. add an instance method
  Vue.prototype.$myMethod = function (methodOptions) {
    // some logic ...
  }
}

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook