vue处理多个异步请求_Vue解决vue-resources异步请求问题

本文介绍了在Vue项目中如何处理多个异步请求的问题,特别是解决在`mounted`生命周期钩子中因数据未及时获取导致的问题。作者提出了一种解决方案,即在数据请求回调成功后设置一个变量,并利用`watch`钩子监听该变量变化来执行相关函数,以确保在正确的时间执行默认选中优惠券的逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

image.png

项目中,这里默认选中优惠券类型的函数,我写在mounted中,但是mounted直接执行话,会因为获取不到ajax请求到的数据,从而判断失败而执行失败;

最开始写法:

defaultSelection()函数需要self.couponId、self.haveReduction、self.haveBalance等参数,但是这些参数都是ajax异步请求之后才获得的,但是此时mounted在ajax还未请求成功渲染完数据的时候,就已经执行结束了,所以导致函数判断失败;

这里,最开始的解决思路有两种:

一、是把请求改为同步,但是这里存在几个问题,1是vue-resources我不知道怎么设置为同步请求,2是这样会造成页面在绑定数据时产生阻塞和卡顿,因此这不是最好的解决方法;

二、在mounted函数设置一个时间定时,大概给个执行时间,延后其执行,但是这样的结果是,如果有时候网络不流畅,数据请求慢,mounted这时已经执行完了,所以也会导致函数执行错误;

三、是我后面选择的解决方法,通过数据请求回掉成功之后,设置一个变量,然后通过watch钩子判断这个变量有没有发生变化,如果检测到发生变化了,这样就执行函数,这样就不会报错了;

最开始代码:

mounted:{

// 默认选中优惠(优先级:满减、优惠券、收益金、基金)

/* setTimeout(function(){

self.defaultSelection();

},200)*/

}

defaultSelection:function () {

var self = this;

if(window.sessionStorage.jumpCouponFlag == "hadIn" && checkAddr.selectDiscount != undefined){

console.log("默认选择优惠券传过来的优惠券");

this.coupon.selectFlag = true;

var oldPrice = checkAddr.orderTotal;

var discountPrice = checkAddr.selectDiscount;

console.log(discountPrice);

if (this.coupon.selectFlag) {

// 优惠券

this.coupon.src = iconed;

if (discountPrice != undefined) {

var couponObj={};

this.total.price = parseFloat(oldPrice) - parseFloat(discountPrice);

couponObj['name']='优惠券抵扣';

couponObj['price']=discountPrice;

if(this.details.length>2){//目前需求就只能选择一种优惠

this.details.pop();

this.details.push(couponObj);

}else{

this.details.push(couponObj);

}

}

}

}else if(self.haveReduction){

this.reduction.selectFlag = true;

window.checkAddr = window.localStorage;

var oldPrice = checkAddr.orderTotal;

var reductionObj={};

reductionObj['name']='满减抵扣';

if (this.reduction.selectFlag) {

this.reduction.src = iconed;

var nowPrice = parseFloat(oldPrice) - parseFloat(this.reduction.cutPrice);

this.total.price = parseFloat(nowPrice);

reductionObj['price']=this.reduction.cutPrice;//抵扣金额>实际金额

if(this.details.length>2){

this.details.pop();

this.details.push(reductionObj);

}else{

this.details.push(reductionObj);

}

}

}else if(self.couponId != ''){

this.coupon.selectFlag = true;

var discountPrice = self.couponPrice;

var oldPrice = checkAddr.orderTotal;

if (discountPrice != 0) {

// 优惠券

this.coupon.src = iconed;

if (discountPrice != undefined) {

var couponObj={};

this.total.price = parseFloat(oldPrice) - parseFloat(discountPrice);

couponObj['name']='优惠券抵扣';

couponObj['price']=discountPrice;

if(this.details.length>2){//目前需求就只能选择一种优惠

this.details.pop();

this.details.push(couponObj);

}else{

this.details.push(couponObj);

}

} else {//不存在就是原来的价钱

this.total.price = parseFloat(oldPrice);

};

}

}else if(self.haveBalance){

this.actives.selectFlag = true;

var oldPrice = checkAddr.orderTotal;

if (this.actives.selectFlag) {

this.actives.src = iconed;

var balanceObj={};

balanceObj['name']='收益抵扣';

var nowPrice = parseFloat(oldPrice) - parseFloat(this.actives.content);

if (parseFloat(nowPrice) < 0) {

this.total.price = 0;

balanceObj['price']=oldPrice;//抵扣金额>实际金额

self.fundBalanceOver = 3; //如果完全抵扣,generate接口支付方式payType需要传参2

} else {

this.total.price = parseFloat(nowPrice).toFixed(2); //四舍五入处理,因为

balanceObj['price']=this.actives.content;//抵扣金额

};

if(this.details.length>2){

this.details.pop();

this.details.push(balanceObj);

}else{

this.details.push(balanceObj);

}

}

}else if(self.haveFund){

this.fund.selectFlag = true;

var oldPrice = checkAddr.orderTotal;

if (this.fund.selectFlag) {

this.fund.src = iconed;

var fundObj ={};

fundObj ['name']='基金抵扣';

var nowPrice = parseFloat(oldPrice) - parseFloat(this.fund.content);

if (parseFloat(nowPrice) < 0) {

this.total.price = 0;

fundObj ['price']=oldPrice;//抵扣金额>实际金额

self.fundBalanceOver = 2; //如果完全抵扣,generate接口支付方式payType需要传参2

} else {

this.total.price = parseFloat(nowPrice).toFixed(2); //四舍五入处理,因为

fundObj ['price']='-'+this.fund.content;//抵扣金额

};

if(this.details.length>2){

this.details.pop();

this.details.push(fundObj );

}else{

this.details.push(fundObj );

}

}

}

}

修改后代码:

watch:{

defaultSelectFlag: 'changeDefaultSelect' //这里设置了一个变量defaultSelectFlag

}

changeDefaultSelect:function(newVal,oldVal){

console.log("改变了,请求默认选中函数");

var self = this;

self.defaultSelection(); //检测到数据加载完了,就执行此函数(代码内容同上)

},

getCouponFlag: function () {//优惠券是否可用

var self = this;

var buyProds = [];

for (var i = 0; i < self.prods.length; i++) {

var buyObj = {}

buyObj["detailId"] = self.prods[i].detailId;

buyObj["buyNum"] = self.prods[i].amount;

buyProds.push(buyObj);

};

console.log(window.JSON.stringify(buyProds));

self.turnbuyPros = buyProds;

console.log(window.JSON.stringify(self.turnbuyPros));

self.$http({

method: 'get',

url: '/mall/coupons/pay',

params: {'prods': window.JSON.stringify(buyProds)},

emulateJSON: true

}).then(function (data) {

var obj = data.data;

if (obj.status == 1) {

var coupons = obj.arrayresult;

var arrCanUse = [];

for (var i = 0; i < coupons.length; i++) {

if (coupons[i].status == 1) {

arrCanUse.push(coupons[i]);

}

};

//从优惠券页面选中优惠券后的显示

if (arrCanUse.length > 0) {

// self.coupon.couponFlag = '可使用';

self.couponId = coupons[0].couponid;

self.couponPrice = coupons[0].discount;

console.log("优惠券");

console.log(self.couponPrice);

console.log(self.couponId);

if(checkAddr.selectDiscount == undefined){

self.appearDiscount = true;

self.coupon.couponFlag = '¥' + self.couponPrice;

}

//

} else {

self.coupon.couponFlag = '不可用';

}

self.defaultSelectFlag = true; // >>>>>数据加载成功,将此变量修改

} else {

// alert(obj.errmsg);

}

}, function (error) {

// window.location.href="http://www.maojimall.com/maojimall/netFail.html";

});

},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值