需求:前端实现倒计时功能,7天免登陆。点击获取验证码按钮后,按钮置灰,90秒后可以再次点击。 当登录到详情页,返回到登录页时,手机号回显,隐藏获取验证码按钮。 当更改手机号时,使用watch监听手机号是否和已经登录的手机号相同。实时动态显示活隐藏获取验证码按钮。
<template>
<div id="epidemicSituation">
<div class="baseBox">
<van-form @submit="onSubmit" ref="codeButton">
<div class="title_login">登录</div>
<van-field
v-model="phone_number"
name="tel_Number"
clearable
show-error="false"
placeholder="请输入手机号"
:rules="[
{ required: true, message: '手机号不能为空' },
{ validator, message: '请输入正确的手机号格式', trigger: 'onBlur' }
]"
>
<template #button v-if="isLogin == '' || tag == true ">
<van-button :class="isSend ? 'sendCode' : 'defaultCode'" size="small" type="default" native-type="button" @click="sendCode" :disabled="isSend">{{sendBtnText}}</van-button>
</template>
</van-field>
<van-field
v-if="isLogin == '' || tag == true "
v-model="code"
name="auth_code"
show-error="false"
clearable
placeholder="请输入短信验证码"
:rules="[
{ required: true, message: '验证码不能为空' },
{ validator: codeValidator, message: '请输入6位正确的短信验证码', trigger: 'onBlur' }
]"
/>
<van-checkbox v-if="isLogin == '' || tag == true " v-model="checked" shape="square" icon-size="16px" >7天内记住我的登录</van-checkbox>
<div style="margin: 16px; border-radius: 4px">
<van-button block type="info" native-type="submit">登录</van-button>
</div>
</van-form>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isSend: false,
sendBtnText: '获取验证码',
checked: false,
timer: null,
counter: 90,
phone_number: '',
code: '',
tag: false
}
},
computed: {
isLogin() {
return '回显的手机号码'
}
},
//监听当前手机号是否与本地存的手机号相同,控制获取验证码按钮显示隐藏
watch: {
phone_number: {
handler( newPhone ) {
this.tag = newPhone != this.isLogin
}
}
},
methods: {
onSubmit() {
},
//获取验证码按钮
sendCode() {
this.$refs.codeButton.validate('tel_Number').then( () => {
//验证码接口
this.getHealthDetail({ phone : this.phone_number })
// 将按钮禁用,防止再次点击
this.isSend = true
// 开始倒计时,60s之后才能再次点击,这里实现倒计时的功能
this.countDown()
}).catch( (e) => {
console.log(e)
})
},
//验证手机号
validator(val) {
return /^1[3-9][0-9]{9}$/.test(val)
},
//验证验证码
codeValidator(val) {
return /^\d{6}$/.test(val)
},
// 倒计时
countDown() {
// 将setInterval()方法赋值给前面定义的timer计时器对象,等用clearInterval()方法时方便清空这个计时器对象
this.timer = setInterval(() => {
// 替换文本,用es6里面的``这个来创建字符串模板,让秒实时改变
this.sendBtnText = `${this.counter}秒后重试`
this.counter--
if (this.counter < 0) {
this.reset()
}
}, 1000)
},
reset() {
// 重置按钮可用
this.isSend = false
// 重置文本内容
this.sendBtnText = '获取验证码'
if (this.timer) {
// 存在计时器对象,则清除
clearInterval(this.timer)
// 重置秒数,防止下次混乱
this.counter = 90
// 计时器对象重置为空
this.timer = null
}
},
// 手机验证码接口
getHealthDetail(data) {
phoneSendSmsAPI(data).then((res) => {
console.log('res', res)
})
},
},
//返回当前页面回显本地手机号
mounted() {
if (this.isLogin) {
this.phone_number = this.isLogin
}
}
}
</script>