Vue 实现通过手机发送短信验证码登录,及60秒倒计时功能
<template>
<div class="wrap">
<el-form
class="loginForm"
:model="loginForm"
:rules="loginFormRules"
ref="loginFormRef"
label-position="top"
>
<el-form-item label="手机号" prop="phone">
<el-input v-model="loginForm.phone"></el-input>
</el-form-item>
<el-form-item label="手机验证码" prop="verificationCode">
<el-input v-model="loginForm.verificationCode">
<template slot="append">
<el-button v-if="loginForm.showloginCode" type="primary" @click="getloginPhoneCode">获取验证码</el-button>
<div v-else>{{ loginForm.count }}</div>
</template>
</el-input>
</el-form-item>
<el-form-item class="btns">
<el-button type="primary" @click="login">登录</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
data() {
var checkMobile = (rules, value, callback) => {
const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
if (regMobile.test(value) == true) {
return callback();
} else {
callback(new Error("请输入合法的手机号"));
}
};
var checkPhoneCode = (rules, value, callback) => {
if (value == this.loginForm.contenttext) {
return callback();
} else {
callback(new Error("验证码错误"));
}
};
return {
loginForm: {
phone: "",
verificationCode: "",
contenttext: "",
timer: null,
showloginCode: true,
count: "",
},
loginFormRules: {
phone: [
{ required: true, message: "请输入手机号", trigger: "blur" },
{ validator: checkMobile, trigger: "blur" },
],
verificationCode: [
{ required: true, message: "请输入手机验证码", trigger: "blur" },
{ validator: checkPhoneCode, trigger: "blur" },
],
},
};
},
methods: {
getloginPhoneCode() {
if (this.loginForm.phone == "") {
return;
}
var numCode = "";
for (var i = 0; i < 4; i++) {
numCode += Math.floor(Math.random() * 10);
}
this.loginForm.contenttext = numCode;
let phoneCode = {
phonenum: this.loginForm.phone,
contenttext: "您正在修改密码,验证码为:" + numCode + ",切勿将验证码泄露给他人。",
};
this.$axios.post("接口地址", phoneCode).then((res) => {
if (res.status != 200) {
return this.$message.error("验证码发送失败!");
} else {
const TIME_COUNT = 60;
if (!this.loginForm.timer) {
this.loginForm.showloginCode = false;
this.loginForm.count = TIME_COUNT;
this.loginForm.timer = setInterval(() => {
if (
this.loginForm.count > 0 &&
this.loginForm.count <= TIME_COUNT
) {
this.loginForm.count -= 1;
} else {
this.loginForm.showloginCode = true;
clearInterval(this.loginForm.timer);
this.loginForm.timer = null;
}
}, 1000);
}
}
});
},
login() {
this.$refs.loginFormRef.validate((valid) => {
if (valid) {
console.log("开始登录");
} else {
console.log("error submit!!");
}
});
},
},
};
</script>
<style scoped>
.loginForm {
width: 500px;
margin: 0 auto;
}
.btns {
text-align: right;
}
</style>