Vue解决vue-resources异步请求问题

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";
        });
      },
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,973评论 19 139
  • 1.几种基本数据类型?复杂数据类型?值类型和引用数据类型?堆栈数据结构? 基本数据类型:Undefined、Nul...
    极乐君阅读 5,601评论 0 106
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,455评论 25 708
  • __block和__weak修饰符的区别其实是挺明显的:1.__block不管是ARC还是MRC模式下都可以使用,...
    LZM轮回阅读 3,370评论 0 6
  • 每个人都会有自己的想法,无论是否会把这些表现于言语或者是展现于行。他们的心里是知道的,有的人能够追寻自己的...
    浮生梦醒阅读 225评论 1 0