vue 实现一个持续时间定时器组件

7 篇文章 0 订阅

vue 实现一个定时器组件

效果图

在这里插入图片描述

子组件

新建一个timer.vue文件

<template>
  <span :class="{red: string >= 600}">{{ string | formatDurationS }}</span>
</template>
<script>

export default {
  name: 'timer',
  props: {
    startTimer: {
      type: [String, Number],
      default: 0
    },
    currentTimer: {
      type: [String, Number],
      default: 0
    }
  },
  data() {
    return {
      string: '--:--:--', // '00:00:00',
      step: 0,
      intervalName: ''
    }
  },
  watch: {
    currentTimer: {
      handler: function(nev, oldv) {
        if (this.intervalName) {
          clearInterval(this.intervalName)
        }
        this.step = this.startTimer
        let _str = Math.round((this.currentTimer - this.startTimer) / 1000)
        this.string = _str < 0 ? 0 : _str
        this.intervalName = setInterval(() => {
          this.string++
        }, 1000)
      },
      immediate: true
    }
  },
  beforeDestroy() {
    clearInterval(this.intervalName)
    this.intervalName = null
  }
}

</script>
<style scoped lang="less">
.red {
  color: #F03E3E;
}
</style>

父组件

导入子组件并注册

<TIMER ref="timerFun" :currentTimer="timeStamp" :startTimer="item.actionTime"></TIMER>


import TIMER from '@/components/timer.vue'

timeStamp: Date.now(),

components: {
  TIMER
}
  • startTimer: 开始计时的时间戳
  • currentTimer: 当前本地时间时间戳
  • 两者的差值就是起始的持续时间
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值