countdown:60,
codeMsg:'获取验证码',
timer:null,
getCode() {
this.$refs.form.validateField('phone',(errMsg)=>{
if(errMsg){
return false
}else {
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;
}
|