我正在寻找一种同时获取多个 URL 的方法。据我所知,API 只能通过单个产品查找来检索我想要的数据,因此我需要使用 url 结构“/products/productID/”一次获取多个产品。注意,这是在 VUEJS 中。这是我的代码到目前为止的样子:
在我的 productServices.js 中:
const productsService = {
getCategory(productID){
const url = `${config.apiRoot}/products/${productID}`
return fetch(url, {
method: 'GET',
headers: {
'content-type': 'application/json',
'Authorization': `Bearer ${authService.getToken()}`
},
})
}
}
在我看来:
data() {
return {
featuredProduct: [13,14,15],
productName: [],
productImg: []
}
}
async mounted(){
const response = await productsService.getCategory(this.featuredProduct)
const resJSON = JSON.parse(response._bodyInit)
this.loading = false
this.productName = resJSON.name
this.productImg = resJSON.custom_attributes[0].value
}
所以我需要点击所有三个 featuredProduct ID 并存储数据。我不太确定如何遍历多个 URL。我的所有其他 API 调用都已使用搜索参数轻松获得所有数据,但对于我在这里需要的特定数据(产品图片),只能通过调用单个产品来查看。
任何帮助深表感谢!
原文由 user3330820 发布,翻译遵循 CC BY-SA 4.0 许可协议
因为您有一系列产品,所以我首先要更改您的州名称:
然后您可以使用 Promise.all 并行获取产品:
You could also consider refactoring
getCategory
do the parsing for you and return an object containing aname
and animage
- that way,mounted
不必了解内部响应结构。