vue.js - vue-router 2, how to fetch routes via ajax? -
how create routes array dynamically, after fetching via ajax?
is there way add/push new routes router after has been initialized?
this doesn't work:
new vue({ el: '#app', template: '<app/>', data: { content: [] }, created: function () { this.$http.get('dummyjsondatafornow').then((response) => { // doesn't work when creating vuerouter() outside vue instance, in docs. // this.$router.options.routes.push({ path: '/about', component: }) let routes = [ { path: '/about', component: } ] // doesn't work either this.router = new vuerouter({ routes: routes }) }) }, // router: router, components: { app } })
i don't believe there no.
that said can wildcard route may provide alternative.
i built site backend (and in turn pages created) controlled via cms served pages vue json. meant vue wasn't aware of routes backend creating.
instead passed cms pages vue router via single *
wildcard component. in vue router 2 like:
const routes = [ { path: '*', component: allpages } ]
vue router 2 allows advanced matching patterns
these allow set wide variety of conditions, therefore whilst can't inject object passed via ajax router can add dynamic component allpages
component wildcard matched. allow pass name of component load via ajax request , load component when page called. i.e.
your ajax response:
{ // url: component name '/about/': 'about', '/about/contact/': 'contact', ... }
then in allpages vue component:
<template> <component v-bind:is="currentview"></component> </template> <script> module.exports = { data () { return { currentview: '', ajaxroutes: {}, // loaded via ajax request ... } }, // watch $route detect page requests watch: { '$route' (to, from) { if (this.ajaxroutes[to]) { this.currentview = this.ajaxroutes[to] } } }, ... } </script>
the above rather abbreviated idea dynamically load component based on path user requested.
Comments
Post a Comment