[Vuejs]-Correct way to install custom VueJs Plugin

0👍

You can add routes dynamically with router.addRoutes() since 2.2.x.

The argument must be an Array using the same route config format with
the routes constructor option.

For example, you can use addRoutes in created hook of the root component:

// your plugin
const myPlugin = {
  install: function(Vue, options) {
    Vue.prototype.$myPlugin = {
      routes: [{
      	path: '/myplugin', component: options.myComponent
      }]
    }
  }
}

// components
const testComponent = { template: '<p>Component called by plugin route</p>' }
const Home = { template: '<p>Default component</p>' }

// router
const router = new VueRouter({
  routes: [{
    path: '/', component: Home
  }]
})

Vue.use(VueRouter)
Vue.use(myPlugin, { myComponent: testComponent })

new Vue({
  el: '#app',
  router,
  created() {
    this.$router.addRoutes(this.$myPlugin.routes); // dinamically add routes
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <button @click="$router.push('/')">Home</button>
  <button @click="$router.push('/myplugin')">Custom</button>
  <router-view></router-view>
</div>

Leave a comment