一般项目接口中很有可能数据分布很不集中,经常出现想要的数据可能在不同对象内。
例如如果要取columns内的数据,以及itemInfo内的部分数据…
按我之前拿数据方法,这样的话就是定义一个对象存放在data内,然后会把columns和itemInfo全部存放在对象内。
今天学习到将所需的数据存入class内,通过带参数的构造函数来实现。
// 将商品基本信息过滤到类中
export class GoodsInfo {
constructor(itemInfo, columns, services) {
this.title = itemInfo.title;
this.desc = itemInfo.desc;
this.newPrice = itemInfo.price;
this.oldPrice = itemInfo.oldPrice;
this.realPrice = itemInfo.lowNowPrice;
this.discount = itemInfo.discountDesc;
this.columns = columns;
this.services = services;
}
然后在要用到数据的组件内导入
再使用
data(){
return {
// 接收商品基本信息
goodsInfo: [],
}
}
methods: {
// 请求商品数据
getDetail(iid) {
getDetail(iid).then(({ data: { result } }) => {
console.log(result);
// 将商品进本信息整合进goodsInfo
this.goodsInfo = new GoodsInfo(
result.itemInfo,
result.columns,
result.shopInfo.services
);
});
},
},