0
votes

I'm using vue-router and have problems with registering components when dynamically importing.
If I use the basic hard coded code, the router will work fine. But if I load my routes in dynamically it fails to render my component.

dynamically importing the component file:

GetAllPages((data) => {
    let pages = [];
    data.map(page => {
        const pageTitle = page.title.rendered.toLowerCase();
        import(`../pages/${pageTitle}.js`).then(module => {
            pages.push({
                path: `/${pageTitle}`,
                name: `${pageTitle}`,
                component: module.default
            })
        })
    })
    return pages;
})

router function:

new VueRouter({
    mode: 'history',
    // routes: pages <= not registering data
    routes: [
        {path: '/about', component: About} // <= working fine
    ]
});

dynamically imported file:

let AboutPage = {
    data: () => ({
        Message: "hey"
    }),
    render: () => {
        return "<h1>{{Message}}</h1>";
    }
}

export default Vue.component("About", {
    data: AboutPage.data,
    template: AboutPage.render()
})

The problem is that the hard coded routes will work, and the dynamically imported pages do not. even if I hard code the dynamically imported values in the data.map function it will not render out my page. There are no errors from the router in the console.

PS: if I console.log the router instance, the dynamiccally imported routes are set. but not rendering html.

1
when you return pages; it'll be an empty array, that will get populated in the future - perhaps that's the issue - how do you use GetAllPages function anyway? You haven't shown that ā€“ Bravo
Pages will not return an empty array. And getalpages is just a api request that will get all pages. Besides that iā€™m not doing much with the request so it is inrelevant to know the return data. And i console logged the instance of the router and all routes are set in that. Just not displaying the html ā€“ Eric
if you think that pages will be fully populated when returned, then you don't understand asynchrony ā€“ Bravo

1 Answers

0
votes

You have two options...

  1. Wait till all your imports resolve before creating your router. This would involve being able to postpone the creation of your root Vue instance
  2. Create your router using lazy-loaded components.

I would recommend option #2

new VueRouter({
  mode: 'history',
  routes: data.map(page => { // data as defined in your GetAllPages function
    const pageTitle = page.title.rendered.toLowerCase()
    return {
      path: `/${pageTitle}`,
      name: pageTitle,
      component: () => import(`../pages/${pageTitle}.js`)
    }
  })
});