vue封装按钮倒计时组件

vue封装按钮倒计时组件

点击按钮之后,间隔一段时间才能重新点击

props:

属性 说明 类型 默认值
text 按钮显示的文本 String 按钮
delayTime 重新点击按钮需要的时间 秒 Number 10

事件 events:

事件名 说明 返回值
click 点击按钮时触发

DelayButton.vue 文件

<template>
  <button
    @click="clickBtn"
    :disabled="!canClickRun"
    :class="{'no-allowed':!canClickRun}"
  >
    {{canClickRun?text:`${text}(${delayTime}s)`}}
  </button>
</template>

<script>
  export default {
    name: "DelayButton",
    props: {
      text: {
        type: String,
        default: "按钮"
      },
      // 重新点击按钮需要的时间 秒
      delayTime: {
        type: Number,
        default: 10
      }
    },
    data() {
      return {
        // 运行爬虫按钮是否能点击
        canClickRun: true,
      }
    },
    methods: {
      clickBtn() {
        // 设置按钮不能点击
        this.canClickRun = false
        // 倒计时,每秒减一,减到 0 时恢复可以点击
        let delay = setInterval(() => {
          this.delayTime -= 1
          if (this.delayTime <= 0) {
            clearInterval(delay)
            this.canClickRun = true
            this.delayTime = 10
          }
        }, 1000)
        // 将点击事件传递到父组件
        this.$emit("click")
      }
    }
  }
</script>

<style scoped>
  button {
    border: 0;
    border-radius: 3px;
    white-space: nowrap;
    padding: 5px 8px;
    cursor: pointer;
    background-color: #008c8c;
    color: #fff;
  }

  /*不能点击时 按钮的样式*/
  .no-allowed {
    cursor: not-allowed;
    background-color: gray;
  }
</style>
posted @ 2020-09-04 16:10  她的开呀  阅读(333)  评论(0编辑  收藏  举报