微信小程序 实现 获取验证码

时间:2024-02-29 22:05:56

WXML 中

<view class="get_yzm" hover-class="none" bindtap="getPhoneSmsByCode">{{limitGetSmsCode.content}}</view>

 

JS 中

data: {
    phone: \'\',
    limitGetSmsCode: {
      enable: true,
      leftSeconds: 60,
      content: "获取验证码"
    }
  },
getPhoneSmsByCode() {
    var _ = this;

    if (!_.data.limitGetSmsCode.enable) {
      wx.showToast({
        title: "请等待" + _.data.limitGetSmsCode.leftSeconds + "后再获取",
        icon: \'none\',
        duration: 1000
      })
      return
    }
    var limitGetSmsCode2 = _.data.limitGetSmsCode
    limitGetSmsCode2.enable = false
    _.setData({
      limitGetSmsCode: limitGetSmsCode2
    })
    //调用发送验证码的接口,对应后台参数
    api.get(\'/api/auth-code/phone\', {
      codeType: "1",
      contentType: "8",
      receiver: this.data.phone
    }).then(res => {
      console.log(res)
      if (res.code == 200) {
        _.checkGetSmsFreq();
        wx.showToast({
          title: res.content.content,
          icon: \'none\',
          duration: 1000
        })
      } else {
        wx.showToast({
          title: res.message,
          icon: \'none\',
          duration: 1000
        })
        var limitGetSmsCode2 = _.data.limitGetSmsCode
        limitGetSmsCode2.enable = true
        _.setData({
          limitGetSmsCode: limitGetSmsCode2
        })
      }
    });
  },
checkGetSmsFreq() {
    var _ = this;
    var c = setInterval(function () {
      var limitGetSmsCode2 = _.data.limitGetSmsCode
      limitGetSmsCode2.content = --limitGetSmsCode2.leftSeconds;
      _.setData({
        limitGetSmsCode: limitGetSmsCode2
      })
      if (_.data.limitGetSmsCode.leftSeconds <= 0) {
        var limitGetSmsCode3 = _.data.limitGetSmsCode
        limitGetSmsCode3.content = "获取验证码";
        limitGetSmsCode3.leftSeconds = 60;
        _.setData({
          limitGetSmsCode: limitGetSmsCode3
        })
        clearInterval(c);
        _.data.limitGetSmsCode.enable = true;
        var limitGetSmsCode4 = _.data.limitGetSmsCode
        limitGetSmsCode4.enable = true;
        _.setData({
          limitGetSmsCode: limitGetSmsCode4
        })
      }
    }, 1000);
  },