微信小程序之定时器实现发送验证码

1.页面代码:

    <van-cell-group>

      <van-field class="phone_div" type="number" value="" name="phone" label="账号" placeholder="请输入你的账号" bindchange="onPhoneChange" />
      <van-button class='="send_code_div"' type="info" disabled="{{disabled}}" bind:click="onSendCode">
        <text class='code_text'>{{codeText}}{{counttime}}{{codeTextLast}}</text>
      </van-button>

      <van-field type="number" value="" name="code" label="验证码" placeholder="请输入验证码" error-message="" border="{{ newPassword }}" bindchange="onCodeChange" />
    </van-cell-group>

2.js代码:

/*定时器*/
function countDown(that, count) {
  if (count == 0) {
    that.setData({
       counttime: '',
       codeText: '获取验证码',
       codeTextLast: '',
       disabled: false
    })
    return;
   }
   that.setData({
    counttime: count
   })
   setTimeout(function () {
    count--;
    countDown(that, count);
   }, 1000);
  0
}

/*验证码按钮事件**/

onSendCode: function() {
    var phone = this.data.phone;
    var that = this;
    if (phone.length <= 0) {
      Dialog.alert({
        message: '请输入电话号码'
      });
      return;
    }
//调用后端发送验证码短信接口
    http.get("/sendPoneCode", {
      mobile: phone
    }, function(err, res) {
      if (res.errCode == -999) {
        Dialog.alert({
          message: '获取验证码失败'
        });
        return;
      }
      if (res.errCode == 0) {
        const toast = Toast.success('获取成功');
        that.setData({
          disabled: true,
          codeText:'',
          codeTextLast:'秒重新获取'
        })
        countDown(that, 60);
      }
    })

  }

/*data参数*/

data: {
    phone: '',
    code: '',
    counttime: '',
    codeText:'获取验证码',
    codeTextLast:'',
    disabled: false
  }

效果展示:

 

 

备注:前端用到了

Vant Weapp组件

地址:https://youzan.github.io/vant-weapp/#/intro

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值