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 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>
Post a Comment for "Correct Way To Install Custom VueJs Plugin"