«
短信验证码定时器

时间:2022-10-12    作者:熊永生    分类: uniapp


模板

<view class="li ac sb p1 w100 bg-white mt-4" :class="shake == 4 && 'shake'">
<view class="c-3"><text class="red">*</text>手机号</view>
<view class="con ac sb c-9">
<u-input v-model="form.phone" placeholder="请输入手机号" clearable border="none"
fontSize="28rpx"></u-input>
<view class="f-24 blue pl-20" @click="$u.throttle(sendSms,1200)">
{{ init_time == time ? '获取验证码':`${time}秒`}}
</view>
</view>
</view>

数据

time:60,
init_time:60,

方法


/**
* 获取验证码
*/
async sendSms() {
let t = this
let {
form,
shakeCss
} = this
if (t.time != t.init_time) {
return shakeCss(4, '还有' + t.time + '秒后可重试')
}
if (t.time == t.init_time) {
if (t.form.phone == '') {
return shakeCss(4, '请输入手机号')
}
if (!uni.$u.test.mobile(t.form.phone)) {
return shakeCss(4, '手机号格式不正确')
}
this.$utils.showLoading()
let {
code,
data,
msg
} = await postSendCode({
phone: t.form.phone
})
this.$utils.hideLoading()
if (code == 200) {
this.showToast(msg, 3000)
} else {
return this.showToast(msg, 3000)
}
}
t.time--
let timer = setInterval(() => {
if (t.time > 1) {
t.time--
} else {
t.time = t.init_time
clearInterval(timer)
}
}, 1000)
},

标签: 标签