likes
comments
collection
share

前端Vue实现手机号验证码登录(60s禁用倒计时)

作者站长头像
站长
· 阅读数 293
引用这篇文章主要介绍了Vue实现手机号验证码登录(60s禁用倒计时),帮助大家更好的理解和使用vue,具有很好的参考价值,感兴趣的朋友可以了解下

最近做了个vue项目,前端通过手机号验证码的方式登录,获取验证码的按钮需要倒计时,点击一次之后,60秒内不能再次点击。先看效果图:

前端Vue实现手机号验证码登录(60s禁用倒计时)

输入正确格式的手机号码后,“获取验证码” 按钮方可点击;点击“获取验证码”后,按钮进入60s倒计时,效果图如下:

前端Vue实现手机号验证码登录(60s禁用倒计时)

前端Vue实现手机号验证码登录(60s禁用倒计时)

效果图有了,接下来就是代码了:

<el-button @click="getCode()"  :disabled="getCodeBtnDisable">{{codeBtnWord}}</el-button>

data返回数据:

data() {
     return {
        loginForm: {
            phoneNumber: '',
            verificationCode: '',
        },
        codeBtnWord: '获取验证码', // 获取验证码按钮文字
        waitTime:60, // 获取验证码按钮失效时间
        getCodeBtnDisable: false,
    }
}

校验手机号是否正确

computed: {
    // 用于校验手机号码格式是否正确
    phoneNumberStyle(){
        let reg = /^1[3456789]\d{9}$/
        if(!reg.test(this.loginForm.phoneNumber)){
            return false
        }
        return true
    }
}

mothods中添加获取验证码方法

async sendCode () {
      try {
        let params = {}
        params.phone = this.loginForm.phoneNumber
        let data = await axios.post('/sendMessage',params)
        this.$message.success('验证码发送成功')
        let that = this
        that.waitTime--
        that.getCodeBtnDisable = true
        this.codeBtnWord = `${this.waitTime}s 后重新发送`
        let timer = setInterval(function () {
          if (that.waitTime > 1) {
            that.waitTime--
            that.codeBtnWord = `${that.waitTime}s 后重新发送`
          } else {
            clearInterval(timer)
            that.codeBtnWord = '获取验证码'
            that.getCodeBtnDisable = false
            that.waitTime = 60
          }
        }, 1000)
      } catch (res) {
        console.log(res)
      }
    },

以上就是Vue实现手机号验证码登录(60s禁用倒计时)的详细内容,如有错误请指出!