【vue】页面须知倒计时定时器组件

1,257 阅读1分钟

<template>
  <div class="component">
    <el-form :model="noticeForm" :rules="rules" ref="noticeForm">
      //.....
      <div class="btn_wrap">
        <el-button @click="handleAgree()" :disabled="checkboxDisabled" type="primary" size="small">
          我已阅读并同意
          <span v-if="num">{{num}}s</span>
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
export default {
   data () {
    return {
     timer: null, //定时器
      num: 5, //倒数几秒
    }
  },
  computed: {
    //倒计时完成开启按钮
    checkboxDisabled () {
      return this.num !== 0
    }
  },
  //打开弹框开始计时
  mounted () {
    this.setNum()
  },
  methods: {
    
    /**
     * @description: 通知父组件关闭
     * @param {type}
     * @return:
     */
    handleDisagree () {
      this.$emit('close')
    },
    
    /**
     * @description: 设置定时器
     * @param {type}
     * @return:
     */
    setNum () {
      this.timer = setInterval(() => {
        console.log('我是定时器,我跑的很快')
        if (this.num > 0) {
          this.num--
        } else {
          this.clearIntervalTimer()
        }
      }, 1000)
      //定时器中途关闭清除计数
      this.$once('hook:beforeDestroy', () => {
        this.clearIntervalTimer()
      })
    },
    clearIntervalTimer () {
      window.clearInterval(this.timer)
    }
  }
}
</script>

<style lang="scss" scoped>
.component {
  color: $color-text;
  .btn_wrap {
    display: flex;
    justify-content: center;
    padding-bottom: 20px;
    /deep/ .el-button {
      margin-left: 16px !important;
    }
  }
}
</style>