精华所在:
(1)计算属性和正则检验手机格式
(2)当满足条件点击发送验证码时,将按钮内容变成倒数60秒,并同时设置disabled="disabled"属性,避免了倒数期间多次发送请求
(3)通过数字是否到0来区别产生组件,是否再次显示发送验证码的内容
代码示例:
<input type="tel" maxlength="11" placeholder="手机号" v-model="phone">
<button
v-if="!countDown"
class="get-verification"
:class="{phone_right: phoneRight}"
@click.prevent="getVerifyCode()"
>
获取验证码
</button>
<button
v-else
disabled="disabled"
class="get-verification">
已发送({{countDown}}s)
</button>
...
data(){
return{
loginMode: true, // 登录方式, true 验证码登录 false 账号登录
phone: '', // 手机号码
countDown: 0, // 倒计时
pwdMode: true, // 密码的显示方式 true 密文 false 明文
pwd: '', // 密码
code: '', // 验证码
userInfo: {}, // 用户的信息
user_name: '', // 用户名
captcha: '', // 图形验证码
}
},
...
computed:{
//验证手机号格式
phoneRight()
{
return /^[1][3,4,5,7,8][0-9]{9}$/.test(this.phone);
}
},
...
getVerifyCode()
{
if(this.phoneRight)
{
this.countDown=60;
let timer=setInterval(()=>{
this.countDown--;
if(this.countDown==0)
{
clearInterval(timer);
}
},1000)
}
}