In this tutorial, you can learn how to develop basic plug-in in Vue application
It is good to have you have basic knowledge on Vue.js
It is very simple to define. An object with install method which has two parameters
Following code shows the basic structure of the plugin. You can name this file as 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. 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
Now we will see how to implement 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 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