背景:在项目中,我们有时候,经常会使用倒计时的功能,这次,我们来制作一个关于短信验证码倒计时的功能。
一、页面结构,然后,绑定点击事件
<div class="div-cell">
<div class="line-cell">
<label class="weui-label">短信验证码</label>
</div>
<div class="line-cell-bd">
<input class="yzm-input1" type="text" v-model="PAY.CAPTCHA" input-limit="12" onkeyup="value=value.replace(/[^A-Za-z0-9]/g,'')">
<i class="g-yzm1" @click="getMessCode()" v-show="currentResult.VcodeFlag == 1">获取验证码</i>
<i class="g-yzm1 pay-yzm-s" v-show="currentResult.VCodeFlag == 2">{{currentResult.countDown}}</i>
<i class="g-yzm1" @click="getMessCode()" v-show="currentResult.VCodeFlag == 3">重发验证码</i>
</div>
</div>
添加CSS样式,如下所示:
.div-cell{
position: relative;
display: flex;
background: #ffffff;
border-bottom: 0.5px solid #ebebeb;
margin: 0 15px;
}
.line-cell{
margin: 0px 5px;
padding: 14px 0px;
height: 17px;
}
.line-cell-bd {
-webkit-box-flex: 1;
flex: 1 1 0%;
margin: 0px 5px;
padding: 14px 0px;
height: 17px;
}
.weui-label {
display: block;
width: 105px;
overflow-wrap: break-word;
word-break: break-all;
color: rgb(45,50,61);
}
.yzm-input1 {
padding-right: 90px;
display: block;
padding-top: 2px;
padding-left: 0;
color: #111;
vertical-align: middle;
font-size: 14px;
}
.g-yzm1 {
width: 82px;
height: 28px;
line-height: 28px;
border: 1px solid #356ae6;
border-radius: 5px;
color: #356ae6;
font-size: 14px;
text-align: center;
right: 0px;
position: absolute;
top: 50%;
transform: translateY(-50%);
z-index: 3;
}
二、js代码部分
export default{
data(){
currentResult:{
codeInput: '', //图形验证码
cardValue: '',
cardName: '',
countDown: '获取验证码', //短信验证码
VCodeFlag: 1,
payTimedown: '', //支付倒计时
},
countdown: '120', //倒计时
timer: null,
},
methods:{
loading(){
//启动定时器
this.countdown--; //定时器减1
this.currentResult.countDown = this.countdown + 's';
},
clearTimer(){
//清除定时器
clearInterval(this.timer);
this.timer = null;
},
//获取短信验证码
getMessCode(){
/*获取验证码倒计时
*VCodeFlag == 1 获取验证码
*VCodeFlag == 2 倒计时
*VCodeFlag == 3 重新获取验证码*/
let that = this;
var busi = {
"PAY": that.PAY,
"operateType": '1',
}
that.TOOL.apiAxios('POST','ZYT_TB_017',busi,function(status,res){
if(status == '1'){
that.currentResult.VCodeFlag = 2;
that.countdown = 120;
that.currentResult.countDown = that.countdown + 's';
that.loading(); //启动定时器
that.timer = setInterval(() => {
//创建定时器
if(that.countdown === 0){
that.clearTimer(); //关闭定时器
that.currentResult.VCodeFlag = 3;
}else{
that.loading();
}
},1000);
MessageBox.alert('验证码已发送!','成功');
}else if(status == '0'){
MessageBox.alert(res.error.msg,'错误');
}
})
}
},
}
相关图片如下所示:
总结:
这样,就在vue项目中,实现了短信验证码倒计时的功能。