首页 / 大前端 / Vue实现获取验证码倒计时

Vue实现获取验证码倒计时

2020-12-24 12:24 大前端 阅读 1271 来源

大体思路跟传统开发差不多,还是利用定时器的方式进项秒数递减,废话不多数直接上代码

<template>
   <div class=container>
       <span v-show="show" @click="getCode">获取验证码</span>
       <span v-show="!show" class="count">{{count}} 秒</span>
    </div>
</template>

这是HTML部分,在这里我定义了两个span,第一个span是实现按钮的功能,第二个span是用来显示秒数,用v-show来实现两个span的交互显示。


export default {
    data() {
        show:
        count: '',
        timer: null, 
    },
    methods:  {
       getCode() {
         const TIME_COUNT = 60
           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)
         }
     },
   }
}

在这里定义定时器,实现count(在这代表秒数)递减,当count小于零的时候清除定时器,并通过show=true显示隐藏秒数,并显示出按钮。

猜你喜欢