vue实现验证码倒计时功能

开发验证码倒计时功能的必要性

  • 主要是为了防止用户频繁的点击,获取短信验证码是有时间限制的,这样就可以让用户在规定的时间内只能点击一次,在客户端就只是告知用户这个什么时候可以点击,在服务端就可以更少的调用这个接口,不去影响服务器的性能
  • 每点击一次都会发送一条短信,也是会收费用的,限制用户点击次数也可以节省费用
  • 设置短信验证码可以定位到目标用户,提高安全性

关键代码

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代码(基于vue2.0)

<script>
export default {
  data() {
    return {
      dis: false,
      show: true,
      isGrey: false, //按钮样式
      timer: null, //设置计时器,
      count: ""
    };
  },
  methods: {
    getCode() {
      let TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.isGrey = true;
        this.show = false;
        this.dis = true;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) { 
            this.count--;
          } else {
            this.dis = false;
            this.isGrey = false;
            this.show = true;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    }
  }
};
</script>

CSS代码

 .grey{
    background-color: #EDEEF1;
    border-color: #EDEEF1;
    color:#666;
    width: 30%;
  }
  .blue{
    background-color: #64A0DD;
    border-color: #64A0DD;
  }
  • 12
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@李优秀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值