一、倒计时基础效果
- 准备 data 数据
data () {
return {
totalSecond: 60, // 总秒数
second: 60, // 倒计时的秒数
timer: null // 定时器 id
}
},
- 给按钮注册点击事件
<button @click="getCode">
{{ second === totalSecond ? '获取验证码' : second + `秒后重新发送`}}
</button>
- 开启倒计时时
async getCode () {
// 当前目前没有定时器开着,且 totalSecond 和 second 一致 (秒数归位) 才可以倒计时
if (!this.timer && this.second === this.totalSecond) {
// 开启倒计时
this.timer = setInterval(() => {
this.second--
if (this.second <= 0) {
clearInterval(this.timer)
this.timer = null // 重置定时器 id
this.second = this.totalSecond // 归位
}
}, 1000)
// 发送请求,获取验证码
this.$toast('发送成功,请注意查收')
}
}
- 离开页面销毁定时器
否则很有可能浪费性能,因为如果不关闭,离开页面的时候倒计时还在进行
destroyed () {
clearInterval(this.timer)
}
二、验证码请求校验处理
- 输入框 v-model 绑定变量
data () {
return {
mobile: '', // 手机号
picCode: '' // 图形验证码
}
},
<input v-model="mobile" class="inp" maxlength="11" placeholder="请输入手机号码" type="text">
<input v-model="picCode" class="inp" maxlength="5" placeholder="请输入图形验证码" type="text">
- methods中封装校验方法
// 校验输入框内容
validFn () {
if (!/^1[3-9]\d{9}$/.test(this.mobile)) {
this.$toast('请输入正确的手机号')
return false
}
if (!/^\w{4}$/.test(this.picCode)) {
this.$toast('请输入正确的图形验证码')
return false
}
return true
},
- 请求倒计时前进行校验
// 获取短信验证码
async getCode () {
if (!this.validFn()) {
return
}
...
}
三、封装接口,请求获取验证码
- 封装接口
api/login.js
// 获取短信验证码
export const getMsgCode = (captchaCode, captchaKey, mobile) => {
return request.post('/captcha/sendSmsCaptcha', {
form: {
captchaCode,
captchaKey,
mobile
}
})
}
- 调用接口,添加提示
// 获取短信验证码
async getCode () {
if (!this.validFn()) {
return
}
if (!this.timer && this.second === this.totalSecond) {
// 发送请求,获取验证码
await getMsgCode(this.picCode, this.picKey, this.mobile)
this.$toast('发送成功,请注意查收')
// 开启倒计时
...
}
}