且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

简单的验证码倒计时功能

更新时间:2022-10-01 09:29:13

之前在公司实习时,主要从事于前端开发。公司当时主要是在开发一个管理系统,关于金融方面的。


前端开发技术主要是用到了vue全家桶、elementUI,以及vue相关的插件等。当时公司是IDEA进行开发,但我推荐用VSCode进行开发,具体还是要按照公司的要求来。


首先说一说验证码计时功能


HTML代码(基于elementUI):


<el-button v-bind:class="{grey:isGrey,blue:!isGrey}" v-bind:disabled="dis" type="primary" 
  @click="getCode">
       <span v-if="show">发送验证码</span><span v-else>重新发送({{count}}s)</span>
  </el-button>

v-bind是vue.js的指令用于绑定数据和元素属性,想具体了解可以去官网查看,这里是用来控制按钮的css样式。


JS代码(基于vue.js);


getCode(){
        this.$refs["form"].validate(valid => {
          if (valid) {
            sendSms(this.form.contactNumber, 120).then(response => {
              if (response.code == 200) {
                this.form.uuid = response.msg;
                this.getCode_Interval()
              }
            })
          }});
      },
      getCode_Interval(second=120)
      {
        this.msgSuccess("验证码已发送到您的手机");
        this.dis=true;
        this.isGrey=true;
        const TIME_COUNT = second;
        if (!this.timer) {
          this.count = TIME_COUNT;
          this.show = false;
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--;
            } else {
              clearInterval(this.timer);
              this.timer = null;
              this.isGrey=false;
              this.show = true;
              this.dis=false
            }
          }, 1000)
        }
      }


在看这段代码如有不懂时可以先去了解vue以及elementUI。


CSS代码:


.grey{
    background-color: #EDEEF1;
    border-color: #EDEEF1;
    color:#666;
    width: 30%;
  }
  .blue{
    background-color: #64A0DD;
    border-color: #64A0DD;
}

参照:Vue实现验证码的60s倒计时_老猫吃饭团的博客-CSDN博客