【响应数据的处理】如何将响应的商品列表数据按照对应的类别,放到数组中
接口(可访问)(POST):https://api.it120.cc/zcr/shop...
接口文档:https://api.it120.cc/doc.html...
请求了商品列表的接口
getGoodsList() { this.axios
.post('/shop/goods/list/v2', {
categoryId: ['263919', '263920', '263921', '263923', '269499', '263924', '263925', '263926', '263927', '263975'],
})
.then(res => {
this.goodsList.push(res.result)
})
},
接口返回的数据是一个数组
需求:把响应的数据以每个类别放到数组中,方便渲染
我使用了以下方法:
// 获取 商品列表 getGoodsList() {
const CATEGORY_ID = ['263919', '263920', '263921', '263923', '269499', '263924', '263925', '263926', '263927', '263975']
for (var i = 0; i < CATEGORY_ID.length; i++) {
this.axios
.post('/shop/goods/list/v2', {
categoryId: CATEGORY_ID[i],
pageSize: 6,
})
.then(res => {
this.goodsList.push(res.result)
})
}
},
<div class="category"> <div class="category-item" v-for="(item, index) in category" :key="item.id">
{{item.name}}
<div class="children">
<div class="children-item" v-for="item1 in goodsList[index]" :key="item1.id">
<a href="#">
<img :src="item1.pic" alt="">
<div class="name">{{item1.name}}</div>
<div class="price">{{item1.minPrice}}元</div>
</a>
</div>
</div>
</div>
</div>
但响应的数据并没有按照我请求参数的顺序来进行排序,导致商品列表与分类不相同
【问:如何将响应的商品列表数据按照对应的类别,放到数组中。我是小白,如果可以请说下具体的代码和描述】
回答:
getGoodsList() { const categoryId = ['263919', '263920', '263921', '263923', '269499', '263924', '263925', '263926', '263927', '263975']
this.axios
.post('/shop/goods/list/v2', {
categoryId: categoryId,
})
.then(res => {
//this.goodsList.push(res.result)
this.goodsList = categoryId.map(item=>{
return (res.result||[]).filter(resItem=>resItem.categoryId === item).slice(0,6);
});
})
},
回答:
this.$set(this.goodsList, i, res.result)
回答:
看图猜代码,建议弄清楚goodsList是全部类别的集合还是个别类别的集合,问题就不是问题了~?
回答:
// 获取 商品列表getGoodsList() {
const CATEGORY_ID = ['263919', '263920', '263921', '263923', '269499', '263924', '263925', '263926', '263927', '263975'];
CATEGORY_ID.forEach((categoryId, index) => {
this.axios.post('/shop/goods/list/v2', {
categoryId: categoryId,
pageSize: 6,
}).then(res => {
this.goodsList.splice(index, 1, res.result);
});
});
},
以上是 【响应数据的处理】如何将响应的商品列表数据按照对应的类别,放到数组中 的全部内容, 来源链接: utcz.com/p/937035.html