[英]Nuxt Dynamic routing from api
I'm having an issue with extendRoutes in nuxt.config.ts我在 nuxt.config.ts 中遇到了 extendRoutes 的问题
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..当我构建我的 nuxt 并生成页面时,我希望我的路由器知道哪个组件基于 api 调用进入哪个路径。
so in Nuxt.config.ts i do this:所以在 Nuxt.config.ts 我这样做:
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".
但是,如果我使用 async/await,我会收到一个 nuxt 错误,说“routes.forEach 不是函数”。
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:一旦我尝试构建,这就会出现此错误:
Well that's not the way how to use async / await
.好吧,这不是使用
async / await
的方式。 It should eliminate .then()
chaining, but you still used it here.它应该消除
.then()
链接,但您仍然在这里使用它。 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.我最终使用了 nuxt 路由器模块( https://github.com/nuxt-community/router-module ),我可以在其中删除 nuxt 路由器并创建自己的路由器。
Here could i use api calls and with await / async and create the logic for the routing i wanted.我可以在这里使用 api 调用和等待/异步并为我想要的路由创建逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.