小程序短信验证码倒计时
wxss文件
给发送短信验证码的接口绑定点击事件getSmsCode,绑定禁用标识disabledBtn,文字用变量btnText代替
<van-cell-group>
<van-field title-width='4em' bindinput="getMobileInput" value="{{mobile}}" center clearable label="手机号" placeholder="请输入手机号码" border="{{ true }}" use-button-slot>
</van-field>
<van-field title-width='4em' bindinput="getCodeInput" value="{{sms}}" center clearable label="验证码" placeholder="请输入短信验证码" border="{{ true }}" use-button-slot>
<van-button bindtap="getSmsCode" disabled="{{disabledBtn}}" slot="button" size="small" type="primary">
{{btnText}}
</van-button>
</van-field>
</van-cell-group>
js文件中
getSmsCode: function () {
var that = this
if (!that.data.mobile) {
wx.showToast({
title: '手机号不能为空',
icon: 'none',
duration: 2000
});
return
}
if (that.data.mobile && that.data.mobile.length != 11) {
wx.showToast({
title: '手机号为11位',
icon: 'none',
duration: 2000
});
return
}
that.setData({
disabledBtn: true, //点击后先按钮禁用
})
wx.showToast({
title: '短信验证码已发送',
icon: 'none',
duration: 2000
});
var currentTime = that.data.currentTime //把手机号跟倒计时值变例成js值
//设置一分钟的倒计时
var interval = setInterval(() => {
currentTime--; //每执行一次让倒计时秒数减一
that.setData({
btnText: currentTime + 's', //按钮文字变成倒计时对应秒数
})
//如果当秒数小于等于0时
if (currentTime <= 0) {
clearInterval(interval) //清除定时器
that.setData({
btnText: '重新发送',
currentTime: 61,
disabledBtn: false,
color: '#59b550'
})
}
}, 1000);
wx.request({
url: Base + '/admin/mobile/' + this.data.mobile,
method: 'get',
success(res) {
console.log("短信验证码的res", res);
//获取验证码失败提示信息
if (res.data.code == 1) {
that.setData({
sms: res.data.msg
})
}
}
})
},