Skip to content Skip to sidebar Skip to footer

Correct Way To Install Custom Vuejs Plugin

Im creating a custom plugin that encapsulates a bunch of authentication functionality with vuex and vue-authenticate. The problem im having is figuring out the correct way to load

Solution 1:

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 pluginconst myPlugin = {
  install: function(Vue, options) {
    Vue.prototype.$myPlugin = {
      routes: [{
      	path: '/myplugin', component: options.myComponent
      }]
    }
  }
}

// componentsconst testComponent = { template: '<p>Component called by plugin route</p>' }
constHome = { template: '<p>Default component</p>' }

// routerconst router = newVueRouter({
  routes: [{
    path: '/', component: Home
  }]
})

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

newVue({
  el: '#app',
  router,
  created() {
    this.$router.addRoutes(this.$myPlugin.routes); // dinamically add routes
  }
})
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script><scriptsrc="https://unpkg.com/vue-router/dist/vue-router.js"></script><divid="app"><button @click="$router.push('/')">Home</button><button @click="$router.push('/myplugin')">Custom</button><router-view></router-view></div>

Post a Comment for "Correct Way To Install Custom Vuejs Plugin"