计时器-vue3

页面效果:动态计时

计时组件代码

<template>
  <!-- 时分秒正计时器 -->
  <div class="father">
    <span>{{ data.one }}<span>:</span></span>
    <span>{{ data.two }}<span>:</span></span>
    <span>{{ data.three }}</span>
  </div>
</template>

<script setup lang="ts">
import { reactive, watch } from 'vue'
const props = defineProps({
  // 计时器开始1 停止2
  isStart: {
    type: Number,
    default: 0
  },
})
const emit = defineEmits(['onStop', 'onStart'])
type dataType = {
  flag: any;
  one: string | number;
  two: string | number;
  three: string | number;
  abc: number;
  cde: number;
  efg: number
}
const data = reactive<dataType>({
  flag: null,
  one: '00', // 时
  two: '00', // 分
  three: '00', // 秒
  abc: 0, // 秒的计数
  cde: 0, // 分的计数
  efg: 0, // 时的计数
})
watch(() => data.three, (newVal) => {
  emit('onStart', { hour: data.one, min: data.two, sec: newVal })
})
watch(() => props.isStart, (newVal) => {
  if (newVal == 1) {
    startHandler()
  } else if (newVal == 2) {
    endHandler()
    emit('onStop', { hour: data.one, min: data.two, sec: data.three })
// 清除时间
    data.one = '00';
    data.two = '00';
    data.three = '00';
    data.abc = 0;
    data.cde = 0;
    data.efg = 0;
  }
})
const startHandler = () => {
  data.flag = setInterval(() => {
    if (data.three === 60 || data.three === '60') {
      data.three = '00';
      data.abc = 0;
      if (data.two === 60 || data.two === '60') {
        data.two = '00';
        data.cde = 0;
        if (data.efg + 1 <= 9) {
          data.efg++;
          data.one = '0' + data.efg;
        } else {
          data.efg++;
          data.one = data.efg;
        }
      } else {
        if (data.cde + 1 <= 9) {
          data.cde++;
          data.two = '0' + data.cde;
        } else {
          data.cde++;
          data.two = data.cde;
        }
      }
    } else {
      if (data.abc + 1 <= 9) {
        data.abc++;
        data.three = '0' + data.abc;
      } else {
        data.abc++;
        data.three = data.abc;
      }
    }

  }, 1000)
}
const endHandler = () => {
  data.flag = clearInterval(data.flag)
}
</script>

<style lang="scss" scoped></style>

使用组件:timeInfo就是返回的动态的时间

<!-- 计时器组件 -->
        <TimeCount :isStart="data.isStart" @onStart="onStart" @onStop="onStop"></TimeCount>
const data = reactive({
  isStart: 0,
  timeInfo: {},
})
// 计时中
const onStart = (val: Object) => {
  data.timeInfo = val
}
// 计时停止
const onStop = (val: Object) => {
  data.timeInfo = val
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值