[英]Nuxt Dynamic routing from api
我在 nuxt.config.ts 中遇到了 extendRoutes 的問題
當我構建我的 nuxt 並生成頁面時,我希望我的路由器知道哪個組件基於 api 調用進入哪個路徑。
所以在 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,
});
}
})
}
}
這會創建一個無限循環,因為但我不等待響應。 但是,如果我使用 async/await,我會收到一個 nuxt 錯誤,說“routes.forEach 不是函數”。
這是異步版本:
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,
});
});
}
一旦我嘗試構建,這就會出現此錯誤:
好吧,這不是使用async / await
的方式。 它應該消除.then()
鏈接,但您仍然在這里使用它。 試試這樣:
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
});
}
}
};
我最終使用了 nuxt 路由器模塊( https://github.com/nuxt-community/router-module ),我可以在其中刪除 nuxt 路由器並創建自己的路由器。
我可以在這里使用 api 調用和等待/異步並為我想要的路由創建邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.