Vue2.x ElementUI登录表单中加入验证码倒计时功能

Vue2.x ElementUI登录表单中加入验证码倒计时功能

在这里插入图片描述

部分Vue代码如下:

<el-form ref="loginForm" :model="loginForm" status-icon :rules="rules" class="login-form">
  <el-form-item label="" prop="code" class="pr">
     <el-input prop="code" v-model="loginForm.code" placeholder="验证码"></el-input>
     <button @click="getCode(regForm)" class="code-btn" :disabled="!show">
        <span v-show="show">发送验证码</span>
        <span v-show="!show" class="count">{{count}} s</span>
     </button>
  </el-form-item>
</el-form>

部分样式代码:

.pr {
   position: relative;
}
.code-btn {
   width: 100px;
   height: 34px;
   position: absolute;
   top: 3px;
   right: 5px;
   z-index: 222;
   color: #F5A623;
   font-size: 14px;
   border: none;
   border-left: 1px solid #bababa;
   padding-left: 16px;
   background-color: #fff;
}

js代码:

<script>
const TIME_COUNT = 60 // 倒计时的时间
export default {
  data () {
    return {
      loginForm: {
        mobile: '',
        code: ''
      },
      show: true,
      count: '',
      timer: null
    }
  },
  methods: {
    getCode (formData) {
      // 验证码倒计时
      if (!this.timer) {
        this.count = TIME_COUNT
        this.show = false
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--
          } else {
            this.show = true
            clearInterval(this.timer)
            this.timer = null
          }
        }, 1000)
      }
    }
  }
}
</script>

好了,以上即实现了验证码倒计时的功能。我这里并没有把这个方法提取出来做公共方法,其实如果多个页面要用的话,建议还是把它抽出来放在工具函数的js文件里面,然后哪个页面需要就import单个方法使用即可。

如果需要在点击之前验证手机号是否填写,在getCode里面加一个判断就可以了。

发布了76 篇原创文章 · 获赞 6 · 访问量 3482

猜你喜欢

转载自blog.csdn.net/weixin_43550660/article/details/103048476