vue--短信验证码

最近在做一个用户预约的功能,其中就是需要对用户进行一个手机号校验。
在form表单中,用户需要填写手机号并通过短信获取验证码
首先

<el-form-item label="" prop="phone">
          <el-input v-model="ruleForm.phone" maxlength="11" placeholder="电话号码" type="text" autocomplete="off" />
          <el-button @click="getCode()">{{ codeBtnWord }}</el-button>//
</el-form-item>
 <el-form-item label="" prop="code">
          <el-input v-model="ruleForm.code" placeholder="验证码:" type="text" autocomplete="off" />
</el-form-item>

在这里插入图片描述
在这里插入图片描述
实现的效果就是:输入电话号码,点击获取验证码,通过接口将短信发送给用户,这个难点就是一分钟的计时器

设定定时器时间初始值为 waitTime = 61

1.点击获取验证码时。 ===是否可点击的情况

  1. 我们需要保证是在用户已经填写好了电话号码,
  2. 就是我们可以做一个临界值,只有当用户填写了电话号码,获取验证码才能够点击,
  3. 点击获取验证码之后,重新获取的时候也是不能点击的,也就是说在60s之内是不能点击的
computed: {
    // 控制获取验证码是否可点击
    getCodeBtnDisable: {
      get() {
        if (this.waitTime === 61) {
          if (this.ruleForm.phone) {
            return false
          } else {
            return true
          }
        } else {
          return true
        }
      },
      set() {}
    }
  },

2.逻辑分析:

  1. 先判断用户输入的电话号码的格式是否正确,如果不正确提示用户输入准确的电话号码格式
  2. 如果输入正确,将用户输入的号码值传给后端,如果接口传递成功,给用法一个成功的弹窗信息:验证码已发送,请稍候。。。
  3. 将定时器进行-1处理,让按钮不能点击,然后启动定时器,进行每隔一秒进行判断,如果waitTime > 1 则waitTime 继续减1,如果小于1 则清除掉定时器
if (/^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/.test(this.ruleForm.phone) === true) {
        const params = {}
        params.phone = this.ruleForm.phone
        // 调用获取短信验证码接口
        sendMess(params).then(res => {
          res = res.data
          // this.ruleForm.code = '1234'
          // if (res.code === 200) {
          this.$message({
            message: '验证码已发送,请稍候...',
            type: 'success',
            center: true
          })
          // }
        })
        // 因为下面用到了定时器,需要保存this指向
        const that = this
        that.waitTime--
        that.getCodeBtnDisable = true
        this.codeBtnWord = `${this.waitTime}s 后重新获取`
        this.timer = setInterval(function() {
          if (that.waitTime > 1) {
            that.waitTime--
            that.codeBtnWord = `${that.waitTime}s 后重新获取`
          } else {
            clearInterval(that.timer)
            that.codeBtnWord = '获取验证码'
            that.getCodeBtnDisable = false
            that.waitTime = 61
          }
        }, 1000)
      } else {
        this.$dialog({
          title: '提示',
          message: '请输入正确的电话号码',
          confirmButtonColor: '#213b73',
          cancelButtonColor: '#1d181c'
        })
      }
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值