<template>
<div class="login">
<van-form @submit="onSubmit">
<van-cell-group inset>
<van-field
v-model="username"
name="手机号码"
label="手机号码"
placeholder="请输入手机号码"
:rules="[{ required: true, message: '请填写手机号码' }]"
/>
<van-field
v-show="true"
v-model="Captcha"
center
clearable
label="短信验证码"
placeholder="请输入短信验证码"
:rules="[{ required: true, message: '请填写验证码' }]"
>
<template #button>
<van-button round plain size="small" type="primary" @click="send" v-show="data.codeShow">发送验证码</van-button>
<van-button round plain size="small" type="primary" v-show="!data.codeShow" disabled >{{data.count}}秒后重试</van-button>
</template>
</van-field>
</van-cell-group>
<div style="margin: 16px;">
<van-button round block type="primary" native-type="submit">
提交
</van-button>
</div>
</van-form>
</div>
</template>
<script>
import 'vant/es/toast/style'
import 'vant/es/notify/style'
import { ref,reactive } from 'vue';
import {getCaptcha} from '@/request/api/home.js'
import { showNotify } from 'vant';
export default {
setup() {
const username = ref(''); //手机号
const Captcha = ref(''); //验证码
const data = reactive({
codeShow: true, //按钮显示
count: '', //倒计时
timer: null, //计时器
})
return {
username,
Captcha,
data
};
},
created(){ //刷新页面时重新取得计时并将计时丢给timeDown执行
let EndTime= sessionStorage.getItem('EndTime');
if(EndTime){
this.timeDown(EndTime);
}
},
methods:{
async send(){
let clicktime = new Date().getTime() + 60000; //未来60秒,这里也毫秒为单位
sessionStorage.setItem('EndTime', JSON.stringify(clicktime)); //存入sessionStorage
let res = await getCaptcha(this.username)
if (res.data.code == 200) {
showNotify({ type: 'success', message: '发送成功' });
this.timeDown(clicktime) //请求成功则触发timeDown并将时间携带过去
}else{
showNotify({ type: 'danger', message:res.data.message });
}
},
timeDown(time){
if (!this.data.timer) {
this.data.count = Math.ceil((JSON.parse(time) - new Date().getTime())/1000); //取出计时
this.data.codeShow = false;
this.data.timer = setInterval(() => {
if (this.data.count > 0) {
this.data.count--;
} else {
this.data.codeShow = true;
clearInterval(this.data.timer); //清除计时器
this.data.timer = null;
sessionStorage.removeItem('EndTime') //计时完后清除sessionStorage
}
}, 1000)
}
},
};
</script>