uniapp 微信小程序 获取验证码 倒计时
1、定义倒计时变量
data() {
return {
defaultTime: '',
model1:{
validateCode:'',
phone:''
}
}
}
2、成功获取验证码后,调用verificationDown函数
// 获取验证码
getVerification() {
// 请求接口获取验证码,然后倒计时
this.$api.appPhone(this.model1.phone).then(res => {
this.verificationTime = 120 // 倒数120秒
this.verificationDown()
})
},
// 倒计时
verificationDown() {
// 设置定时器
this.timer = setInterval(() => {
this.verificationTime = this.verificationTime - 1
if (this.verificationTime < 10) this.verificationTime = '0' + this.verificationTime
if (this.verificationTime <= 0) {
// 清除定时器
clearInterval(this.timer)
this.verificationTime = ''
}
}, 1000)
},
3、页面展示
<u-form-item labelWidth="120rpx" label="手机号" prop="phone" ref="item1">
<view class="name">
<u-input type="number" class="name_inp" v-model="model1.phone" placeholder="请输入手
机号" :border="false" >
</u-input>
</view>
</u-form-item>
<u-form-item labelWidth="120rpx" label="验证码" prop="validateCode" ref="item1">
<view class="name">
<u-input type="number" class="name_inp" v-model="model1.validateCode"
placeholder="请输入验证码" :border="false">
</u-input>
<button type="default" size="mini" v-if="!verificationTime"
style="margin: 0;margin-left: 20rpx;color: #fff;background: #19be6b;border:0;
padding: 0 20rpx;"
@click="getVerification">获取验证码
</button>
<button type="default" size="mini" v-if="verificationTime" disabled="true"
style="margin: 0;margin-left: 20rpx;background: #79be75;color: #fff;border:0;
padding: 0 20rpx;" @click="verification">重新获取
{{verificationTime}}s
</button>
</view>
</u-form-item>