一般在多标签页面请求数据时,请求完毕后,将数据保存下来,以便下一次调用。
如图所示,我需要请求左侧列表中的数据(getCategory),请求后请求于内容区域上部分的(getSubCategory),最后请求内容区域下部分的(getRecommend)区域。
// 获取分类的详情数据(Category)
_getCategory() {
getCategory().then((res) => {
this.categories = res.data.category.list;
// 初始化每个分类的子数据,将当前数据放入categoryData中
for (let i = 0; i < this.categories.length; i++){
this.categoryData[i]={
subCategoryData:{},
categoriesDetail:{
'pop':[],
'new':[],
'sell':[]
}
}
}
//当该操作完成后直接进行下一部分的请求
//默认请求index为0的数据
this._getSubcategory(0);
});
}
//获取内容的详情分类数据(subCategory)
_getSubcategory(index) {
this.currentIndex = index;
this.maitKey = this.categories[index].maitKey;
getSubcategory(this.maitKey).then((res) => {
//将请求下来的结果放入categoryData对象中
this.categoryData[index].subCategoryData = res.data;
this.categoryData = { ...this.categoryData };
// 请求接下来的推荐数据
this._getRecommend("pop");
this._getRecommend("sell");
this._getRecommend("new");
});
}
//获取推荐数据(recommend)
_getRecommend(type) {
const miniWallkey = this.categories[this.currentIndex].miniWallkey;
getCategoryDetail(miniWallkey, type).then((res) => {
//将请求下来的数据放入对应的type中
this.categoryData[this.currentIndex].categoriesDetail[type] = res;
this.categoryData = { ...this.categoryData };
});
},
而在向子组件中传入数据时,不直接传入res,而是将categoryData作为计算属性传入。
<category-data :subCategoryData="showSubCategoryData"></category-data>
<GoodList :goods="showRecommend" class="recommend"></GoodList>
computed: {
showSubCategoryData() {
if (this.currentIndex === -1) return {};
return this.categoryData[this.currentIndex].subCategoryData;
},
showRecommend() {
if (this.currentIndex === -1) return {};
return this.categoryData[this.currentIndex].categoriesDetail[
this.currentType
];
},
}