Vue - 实现通过手机发送短信验证码登录

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;
      }
      // 获取随机数(4位数字)
      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 {
          // 当验证码发送成功,开始60秒倒计时
          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>
### Vue短信验证码登录实现 #### 后端逻辑处理 在后端部分,当接收到请求时,在业务层生成随机字符串作为验证码,并通过调用第三方服务完成实际的消息发送操作。为了保证安全性与有效性,通常会将此验证码存储于缓存数据库如Redis内一定时间范围以便后续验证[^1]。 ```python import random import redis def send_verification_code(phone_number): code = &#39;&#39;.join([str(random.randint(0, 9)) for _ in range(6)]) # Generate a six-digit verification code rds = redis.Redis(host=&#39;localhost&#39;, port=6379, db=0) try: # Store the generated code into Redis with an expiration time of five minutes. rds.setex(f&#39;verification:{phone_number}&#39;, 300, code) # Call SMS sending tool class method to actually send out the message (omitted here). return True except Exception as e: print(e) return False ``` #### 前端Vue组件设计 对于前端而言,则需创建专门用于展示和交互的Vue组件来负责发起获取验证码请求、倒计时控制等功能。这里可以通过`axios`库来进行HTTP通信;利用定时器机制管理按钮状态变化及等待期间的文字提示更新等行为[^3]。 ```html <template> <div id="verification-code"> <!-- Other form elements --> <button @click.prevent="requestCode()" :disabled="isCounting">{{ buttonText }}</button> <!-- Rest parts omitted --> </div> </template> <script> export default { data() { return { phoneNumber: &#39;&#39;, remainingTime: 0, intervalId: null, }; }, computed: { isCounting() {return this.remainingTime > 0;}, buttonText(){ if(this.isCounting){ return `${this.remainingTime}s later resend`; }else{ return &#39;Get Verification Code&#39;; } } }, methods: { async requestCode() { const response = await axios.post(&#39;/api/sendVerificationCode&#39;, {phoneNumber:this.phoneNumber}); if(response.data.success === true){ let countDownSeconds = 60; clearInterval(this.intervalId); this.remainingTime = countDownSeconds; this.intervalId = setInterval(() => { if (--countDownSeconds >= 0) { this.remainingTime = countDownSeconds; } else { clearInterval(this.intervalId); } }, 1000); } // Handle error cases... } } } </script> ```
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值