HTML:
<div class="item">
<input type="text" v-model="phone" placeholder="请输入手机号">
</div>
<div class="item phone-code">
<input type="text fl" v-model="phone_sms_valid_code" placeholder="请输入手机验证码">
<button class="btn fr" @click="countDown">{{content}}</button>
</div>
js:
export default {
data() {
return {
content: '获取验证码',
totalTime: 60,
canClick: true, //添加canClick
phone:'',
}
},
methods: {
countDown() {//获取验证码
if(!this.canClick) return;
if(!this.phone){
alert("请输入手机号");
return false;
}
if(!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(this.phone)) {
alert("请输入正确的手机号");
return false;
}
this.$axios.get('/act/sms/' + this.phone).then((res) => {
if(res.success) {
this.canClick = false
this.content = this.totalTime + 's后重新发送';
let timer = window.setInterval(() => {
this.totalTime--
this.content = this.totalTime + 's后重新发送';
if(this.totalTime < 0) {
window.clearInterval(timer);
this.content = '重新发送验证码'
this.totalTime = 60
this.canClick = true //这里重新开启
}
}, 1000);
} else {
alert(res.msg);
}
})
},
}
}
element
countDown() {
//获取验证码
if (!this.canClick) return;
if (!this.form.phonenumber) {
this.$message.error("请输入手机号");
return false;
}
if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(this.form.phonenumber)) {
this.$message.error("请输入正确的手机号");
return false;
}
getSmsCode({ phonenumber: this.form.phonenumber })
.then((res) => {
if (res.code == 200) {
this.canClick = false;
this.content = this.totalTime + "s后重新发送";
let timer = window.setInterval(() => {
this.totalTime--;
this.content = this.totalTime + "s后重新发送";
if (this.totalTime < 0) {
window.clearInterval(timer);
this.content = "重新发送验证码";
this.totalTime = 60;
this.canClick = true; //这里重新开启
}
}, 1000);
} else {
this.$message.error(res.msg);
}
})
.catch((err) => {
console.log("getSmsCode err", err);
});
},
转载请注明:有爱前端 » Vue 获取验证码60s倒计时方法