Build a VUE plugin

ManiKanta Koppala
Vue.js Developers
Published in
2 min readFeb 9, 2020

(Note: This is one of the articles written in a series of vue plugin-based development. If you are new, please check out the whole story, or if you want to know only about building a vue plugin, please continue)

Photo by Glen Carrie on Unsplash

Have you ever used vue.use(router)? Any vue application can use the router plugin. It’s pretty easy to build a plugin. Our entry file should export the default method install. Let’s see our index.js file our one of the plugin

export default {
install(Vue, options) {
//Where Vue is the global vue instance and
//options are extra parameters we pass while using plugin
//Vue.canAddGlobalMethods = () => {}
//Vue.directive('my-directive.....
//mixins, instances and many more
}
};

Inside that install method, we can do whatever we want. We can extend vue with our custom routes, store, and many more.

Since in our journey, we are building a complete vue application as a plugin, we have to find a way to extend main application routes, store (also i18n). Vue option inside the install method is a global instance that doesn’t have any context of the application routes and store. So whoever is consuming our plugin has to pass the following properties.

Vue.use(newsfeed, {
router: router,
store: store,
i18n: i18n,
});

We require the consumer application router, store & i18n so that we can extend them as follows,

So we are adding routes using addRoutes, store using registerModule & i18n using mergeLocaleMessage. These are the methods provided by those individual plugins. Here are the router.js and store.js looks like inside the plugins

router.js
store.js

(Note: if you observe we are not exporting new Vuex.Store() for the store and also new Router for the router. Instead, we are just exporting our plain routes and store which we are extending them with application route and store)

Summary

We injected a complete application (routes, store & i18n) into another application. So any vue application can install our package and use it by passing the information required.

Let’s see in our next journey how we can inject these plugins in a better way.

--

--