最近在做一个Vue项目,前端通过手机号、验证码登录,获取验证码按钮需要设置60s倒计时(点击一次后,一分钟内不得再次点击)。先看一下效果图:

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

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

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

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

 效果图已经有了,接下来就上代码吧!

  • html
<el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}" :disabled="getCodeBtnDisable">{{codeBtnWord}}</el-button>
  • 数据data
data() {
     return {
        loginForm: {
            phoneNumber: '',
            verificationCode: '',
        },
        codeBtnWord: '获取验证码', // 获取验证码按钮文字
        waitTime:61, // 获取验证码按钮失效时间
    }
}
  • 计算属性computed
computed: {
    // 用于校验手机号码格式是否正确
    phoneNumberStyle(){
        let reg = /^1[3456789]\d{9}$/
        if(!reg.test(this.loginForm.phoneNumber)){
            return false
        }
        return true
    },
    // 控制获取验证码按钮是否可点击
    getCodeBtnDisable:{
        get(){
            if(this.waitTime == 61){
                if(this.loginForm.phoneNumber){
                    return false
                }
                return true
            }
            return true
        },
        // 注意:因为计算属性本身没有set方法,不支持在方法中进行修改,而下面我要进行这个操作,所以需要手动添加
        set(){} 
    }
}

关于上面给计算属性添加set方法,可以参照//www.jb51.net/article/202496.htm

  •  css设置不可点击时置灰
.el-button.disabled-style {
    background-color: #EEEEEE;
    color: #CCCCCC;
}
  • mothods中添加获取验证码方法
getCode(){
    if(this.phoneNumberStyle){
        let params = {}
        params.phone = this.loginForm.phoneNumber
        // 调用获取短信验证码接口
        axios.post('/sendMessage',params).then(res=>{
            res = res.data
            if(res.status==200) {
                this.$message({
                    message: '验证码已发送,请稍候...',
                    type: 'success',
                    center:true
                })
            }
        })
        // 因为下面用到了定时器,需要保存this指向
        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 = 61
            }
        },1000)
    }
}

通过上面的代码,就可以实现了,如有错误,敬请指正!

以上就是Vue实现手机号、验证码登录(60s禁用倒计时)的详细内容,更多关于vue 手机号验证码登录的资料请关注其它相关文章!

标签:
vue,验证码登录,vue,手机号登录,vue,登录禁用倒计时

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
桃源资源网 Design By www.nqtax.com