倒计时组件,传参接受Date 对象或一个表示时间戳的数字

这个倒计时组件 (CountDown) 是一个 Vue 组件,用于显示从当前时间到指定目标时间的倒计时。组件接受一些属性(props),并在内部通过定时器不断更新倒计时的时间。以下是组件的详细用法和解释:

组件用法

组件内部实现

  1. 引入组件: 在使用组件之前,需要先在项目中引入它。假设你已经创建了这个组件文件(例如 CountDown.vue),你可以在需要使用它的父组件中引入并注册它。
     

    <template>
      <span>
        {{ lastTime | format }}
      </span>
    </template>
    
    <script>
    
      function fixedZero(val) {
        return val * 1 < 10 ? `0${val}` : val;
      }
    
      export default {
        name: "CountDown",
        props: {
          format: {
            type: Function,
            default: undefined
          },
          target: {
            type: [Date, Number],
            required: true,
          },
          onEnd: {
            type: Function,
            default: () => {
            }
          }
        },
        data() {
          return {
            dateTime: '0',
            originTargetTime: 0,
            lastTime: 0,
            timer: 0,
            interval: 1000
          }
        },
        filters: {
          format(time) {
            const hours = 60 * 60 * 1000;
            const minutes = 60 * 1000;
    
            const h = Math.floor(time / hours);
            const m = Math.floor((time - h * hours) / minutes);
            const s = Math.floor((time - h * hours - m * minutes) / 1000);
            return `${fixedZero(h)}:${fixedZero(m)}:${fixedZero(s)}`
          }
        },
        created() {
          this.initTime()
          this.tick()
        },
        methods: {
          initTime() {
            let lastTime = 0;
            let targetTime = 0;
            this.originTargetTime = this.target
            try {
              if (Object.prototype.toString.call(this.target) === '[object Date]') {
                targetTime = this.target
              } else {
                targetTime = new Date(this.target).getTime()
              }
            } catch (e) {
              throw new Error('invalid target prop')
            }
    
            lastTime = targetTime - new Date().getTime();
    
            this.lastTime = lastTime < 0 ? 0 : lastTime
          },
          tick() {
            const {onEnd} = this
    
            this.timer = setTimeout(() => {
              if (this.lastTime < this.interval) {
                clearTimeout(this.timer)
                this.lastTime = 0
                if (typeof onEnd === 'function') {
                  onEnd();
                }
              } else {
                this.lastTime -= this.interval
                this.tick()
              }
            }, this.interval)
          }
        },
        beforeUpdate () {
          if (this.originTargetTime !== this.target) {
            this.initTime()
          }
        },
        beforeDestroy() {
          clearTimeout(this.timer)
        }
      }
    </script>
    
    <style scoped>
    
    </style>

    组件属性(Props)

  2. target

    • 类型:Date 或 Number(毫秒数)
    • 必须:是
    • 描述:倒计时的目标时间。可以是一个 Date 对象或一个表示时间戳的数字。
  3. format

    • 类型:Function
    • 默认值:无
    • 描述:自定义格式化时间的函数。如果未提供,默认使用组件内置的格式化函数。
  4. 数据属性

    • dateTime:初始时间字符串,设置为 '0'
    • originTargetTime:存储原始的目标时间,用于比较目标时间是否发生变化。
    • lastTime:剩余时间(毫秒)。
    • timer:定时器 ID。
    • interval:定时器间隔时间,默认为 1000 毫秒(1 秒)。
  5. 过滤器

    • format:格式化时间的过滤器,将剩余时间转换为 HH:mm:ss 格式。
  6. 生命周期钩子

    • created:在组件实例创建完成后立即调用,初始化时间和启动定时器。
    • beforeUpdate:在组件更新之前调用,检查目标时间是否发生变化,如果变化则重新初始化时间。
    • beforeDestroy:在组件销毁之前调用,清除定时器。
  7. 方法

    • initTime:初始化倒计时时间,计算从当前时间到目标时间的剩余时间。
    • tick:每秒更新一次倒计时时间,如果倒计时结束则触发 onEnd 回调并停止定时器。
  8. onEnd

    • 类型:Function
    • 默认值:空函数
    • 描述:倒计时结束时触发的回调函数。

详细代码解释

  • fixedZero 函数:确保时间单位不足两位时前面补零。
  • data:定义组件的数据属性。
  • filters:定义格式化时间的过滤器。
  • created:初始化时间和启动定时器。
  • methods
    • initTime:初始化倒计时时间。
    • tick:每秒更新一次倒计时时间。
  • beforeUpdate:检查目标时间是否发生变化,如果变化则重新初始化时间。
  • beforeDestroy:清除定时器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值