//先定义
//倒计时秒数
countdown:60,
//按钮上的文字
codeMsg:'获取验证码',
//定时器
timer:null,
//函数
// 获取验证码
getCode() {
this.$refs.form.validateField('phone',(errMsg)=>{
if(errMsg){
return false
}else {
// 验证码60秒倒计时
if (!this.timer) {
this.$axios.post(urlGetSmsCode,{'name':this.ruleForm.phone}).then(res=>{
if(res.code===200){
this.setTime()
this.$message.success(`发送成功`)
}else{
this.$message.error(res.msg)
}
}).catch(res=>{
this.$message.error(res.data.message)
})
}
}
})
},
//倒计时
setTime(){
let _this = this;
this.timer = setInterval(() => {
if (_this.countdown > 0 && _this.countdown <= 60) {
_this.countdown--;
if (_this.countdown !== 0) {
_this.codeMsg = "重新发送(" + _this.countdown + ")";
} else {
clearInterval(_this.timer);
_this.codeMsg = "获取验证码";
_this.countdown = 60;
_this.timer = null;
}
}
}, 1000)
},
最后在用beforeDestroy函数去掉定时器
beforeDestroy() {
clearInterval(this.timer);
this.timer = null;
}