简体   繁体   中英

Nuxt Dynamic routing from api

I'm having an issue with extendRoutes in nuxt.config.ts

When i build my nuxt and generate pages i want my router to know which comonent goes to which path based on an api call..

so in Nuxt.config.ts i do this:

 router: {
  extendRoutes(routes resolve){
    cms.getRoutes().then(x => { <-- this returns an array from api call with objects needed for path
       for(var i = 0; i < x.items.lenth; i++){
         routes.push({
            name: x.items[i].name,
            component: component: resolve(__dirname, `pages/index.vue`), <- this is just and ex. of comp.
            path: x.items[i].slug,
         });
       }
    })
  }
}

This creates an inifinite loop because but i dont await the response. But if I use async/await i get an nuxt error saying "routes.forEach is not a function".

Here is the async version:


async extendRoutes(routes: any, resolve: any) {

        await cms.GetSitemap().then((x: any) => {
            for(var i = 0; i < x.items.lenth; i++){
             routes.push({
               name: x.items[i].name,
               component: component: resolve(__dirname, `pages/index.vue`),
               path: x.items[i].slug,
             });
        });
    }

this gives this error as soon as i try to build:

异步 / 等待上的 nuxt 错误

Well that's not the way how to use async / await . It should eliminate .then() chaining, but you still used it here. Try it like this:

router: {
  async extendRoutes(routes, resolve) {
    let x = await cms.getRoutes();
    for (var i = 0; i < x.items.length; i++) {
      routes.push({
        name: x.items[i].name,
        component: resolve(__dirname, `pages/index.vue`),
        path: x.items[i].slug
      });
    }
  }
};

I ended up using the nuxt router module ( https://github.com/nuxt-community/router-module ) where i could remove the nuxt router and create my own.

Here could i use api calls and with await / async and create the logic for the routing i wanted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM