samedi 27 juillet 2019

Issue with dynamicallly router.addRoutes importing Component

I'm currently playing around with Vue using Laravel as Backend. I've setup a Page Model, where each Page can have "children".

Now I'm trying to build the routes for vue-router dynamically.

Note: This is inline script within my Blade Template, no webpack or babel!

    <body>
        <div id="app">
        <router-link v-for="route in routes" :to="route.path" :key="route.name">@
            <router-link  v-for="child in route.children" :to="child.path" :key="child.name">@</router-link>
        </router-link>
        <router-view></router-view>
        </div>
    </body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://unpkg.com/axios@0.2.1/dist/axios.min.js"></script>

<script type="module">
Vue.use(VueRouter);
let routes = [];

const router = new VueRouter({ routes});

window.app = new Vue({
    el: '#app',
    router,
    created(){
        axios.get('/pages').then(r => this.createRouting(r));
    },
    methods:{
        createRouting(pages){
           let vm = this

           pages.forEach(function(page){
                vm.routes.push(vm.makeRoute(page))
           })
           vm.$router.addRoutes(vm.routes)

        },
        makeRoute(page){
            let vm = this
            let route = {}
            route.path = page.slug
            route.name = page.name
            route.component = () => import('/js/Test.js')
            if(page.children.length){
                route.children = []
                page.children.forEach(function(child){
                    route.children.push(vm.makeRoute(child))
                })
            }
            return route
        }
    }
});
</script>

This works, except the router-view is not showing the Component. The router-links show up as expected. And I can see all routes in Vue Dev Tools under Routing.

I tried to hardcode one route, to verify the import works and dynamically add the others.

let routes = [    
    {
        path:'/',
        component:() => import('/js/Test.js')
    }
];

This shows the Test Component on the / route, but all other routes show a blank router-view <!---->

In Vue Dev Tools, the component of the first route shows:

component:ƒ component()

All other routes show:

component:ƒ ()

Test.js Component:

let Test = Vue.component('Test',{
    template:`<div>Foo</div>`
});
export default Test;



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire