VUE倒计时组件

常用于发送短信、邮件后1分钟倒计时,倒计时结束后又可以再次点击

vue组件封装:

<template>
  <div class="timer-btn">
    <button
      class="sendSmsBtn"
      :class="disabled?'disableSendSmsBtn':''"
      type="button"
      @click="run"
      :disabled="disabled || time > 0"
    >{{ text }}</button>
  </div>
</template>

<script>
export default {
  name: 'TTimer',
  props: {
    second: {
      type: Number,
      default: 60
    },
    start: {
      type: Boolean,
      default: false,
    }
  },
  watch: {
    start(status) {
      if (status) {
        this.go()
      }
    },
  },
  data() {
    return {
      time: 0,
      disabled: false
    }
  },
  computed: {
    text() {
      return this.time > 0 ? `${this.time}s 后重获取` : '获取验证码'
    }
  },
  methods: {
    run() {
      this.$emit('click')
    },
    go() {
      this.time = this.second
      this.disabled = true
      this.timer()
    },
    timer() {
      if (this.time > 0) {
        this.time--
        setTimeout(this.timer, 1000)
      } else {
        this.disabled = false
        this.$emit('end')
      }
    }

  }
}
</script>
<style lang="scss" scoped>
.timer-btn {
  position: relative;
  .sendSmsBtn {
    height: 40px;
    line-height: 40px;
    border-radius: 4px;
    font-size:14px;
    background-color:#ecf5ff;
    border: 1px solid #b3d8ff;
    padding: 0 6px;
    color: #409eff;
    font-weight: 500;
    display: inline-block;
    width:100%;
    min-width: 92px;
    cursor: pointer;
  }
  .disableSendSmsBtn {
    opacity: 0.5;
    cursor: auto;
  }
}
</style>

调用
<t-timer v-else :second="60" @click="getCode" :start="startCountdown" @end="handleEnd"/>

我这儿用的getCode方法请求后台短信、startCountdown标志true或false状态可以开始啦, handleEnd方法用来标记倒计时结束后修改startCountdown状态

标签: VUE, Javascript

相关文章

在HTML中为 h1-h6 标签添加序号及颜色背景色块

在HTML结构中,h1 到 h6 是常见的标题标签,通常我们会希望对这些标题进行标注或编号,使其更具层次感。在这篇文章中,我将向您展示如何通过纯JavaScript自动为 h1 到 h6 标签添...

JAVA+VUE的多国语言跨境电商外贸商城源码

多语言跨境电商外贸商城TikTok内嵌商城,商家入驻、一键铺货、一键提货 全开源完美运营海外版抖音TikTok商城系统源码,TikToK内嵌商城,跨境商城系统源码接在tiktok里面的商城。ti...

图片Base64编码

CSR生成

图片无损放大

图片占位符

Excel拆分文件