<template>
<el-card class="box-card">
<div slot="header" class="clearfix">
<span>用户登录</span>
</div>
<el-form>
<el-form-item>
<el-input v-model="phoneNumber" placeholder="请输入手机号">
<el-button slot="append" @click="getVerifyCode" :disabled="disabled">{{btnTitle}}</el-button>
</el-input>
</el-form-item>
<el-form-item>
<el-input v-model="verifyCode" placeholder="请输入验证码"></el-input>
</el-form-item>
<el-button type="primary" @click="onSubmit">登录</el-button>
</el-form>
</el-card>
</template>
<script>
export default {
name: "",
data() {
return {
phoneNumber: "",
verifyCode: "",
disabled: false,
btnTitle: "获取验证码",
temp:""
};
},
methods: {
onSubmit() {
if(this.verifyCode==this.temp){
console.log("登录成功,本次验证码是:"+this.temp);
}else{
console.log("登录失败")
}
},
getVerifyCode() {
let time = 30;
let timer = setInterval(() => {
this.btnTitle = time + "秒后重试";
this.disabled = true;
time--;
if (time == 0) {
clearInterval(timer);
this.btnTitle = "获取验证码";
this.disabled = false;
}
}, 1000);
this.temp=Math.floor(Math.random()*100000)+100000;
let regUrl =
this.JUHE_API +
`/json?key=m4riqdf3&secret=kLbF9WFT&from=pingda&to=86${this.phoneNumber}&text=【济源晨报】本次验证码是:${this.temp},请不要告诉他人哦!`;
this.$Axios.get(regUrl).then(res => {
console.log(res);
});
}
}
};
</script>
<style lang="scss" scoped>
.el-input-group__append {
.el-button {
padding: 4px;
}
}
.el-button.is-disabled, .el-button.is-disabled:focus, .el-button.is-disabled:hover{
background: none;
}
</style>
使用elementui制作的登录框card,定义一个随机六位数数字验证码
通过短信api给输入的手机号,发送随机验证码,保存这个随机数
验证码输入后,输入框的值和保存的随机数做比较,相等即表示验证码正确
由于vue是单页面应用,
某个页面内使用定时器时,需要把定时器定义在data全局,timer:null
当需要使用时给this.timer赋值
另外,在页面组件生命周期里,需要离开页面时把定时器清理掉
regetverifyCode() {
if(this.timer){
clearInterval(this.timer);
this.verifyCodeText = "获取验证码";
}
let time = 59;
this.timer = setInterval(() => {
this.verifyCodeText = `获取验证码(${time}s)`;
this.isCanRegetverifyCodeFlag = true;
time--;
if (time == 0) {
clearInterval(this.timer);
this.verifyCodeText = "获取验证码";
this.isCanRegetverifyCodeFlag = false;
}
}, 1000);
},
//另外,在页面组件生命周期里,需要离开页面时把定时器清理掉
beforeDestroy() {
if(this.timer) {
clearInterval(this.timer);
}
}