Basic Plugin development with Vue.js
In this tutorial, you can learn how to develop a basic plug-in for Vue application
You need to have a basic knowledge of Vue.js to continue this article.
What is Vue plug-in
It is very simple to define. An object with an install method that has two parameters
What you can do with Vue Plugin?
-
- Vue plugin enables you to add global level functionality to your Vue application
- You can keep your code clean and small
- You can share the code with other application and developers
Skeleton of the plugin
The following code shows the basic structure of the plugin. You can name this file the MyPlugin.js
// MyPlugin.js // This exports the plugin object. export default { // The install method will be called with the Vue constructor as // the first argument, along with possible options install (Vue, options) { } }
In this example, you first export the plugin object so that you can use the plugin anywhere in your application
You can find the install
method which takes two arguments. The first argument is the Vue
and second arguments is the optional parameters which can be passed into the plugin
Inside the install method, you can use one or more of the following things
-
- (a) Add some global methods
- (b) Add global assets like directives, filters, transitions etc
- (c) Add custom components by using global Mixin
Now we will see how to implement the above cases
(a) Add global method
This is how you define the instance method. You can simply add the method inside the install()
export default { install (Vue, options) { Vue.prototype.$myFunction = function () { return "Instance Method" } } }
You can use call this method inside the template tag or script tag as shown in the below diagram
// inside template {{$myFunction()}} //inside script $myFunction()
(b) Add directives and filters
You can see the directive code inside the install method of the plugin
export default { install (Vue, options) { Vue.directive('mydirective', { bind (el, binding, vnode, oldVnode) { el.style.color='red' } })
Once you define the directive, you can use it in your template as shown below
Hello
(c) Add components
import MyComponent from './MyComponent.vue'; const MyPlugin { install(Vue, options) { Vue.component('my_component', MyComponent) } }
Now you can use the my_component in your application wherever you need