time-clock.vue 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <template>
  2. <div class="time-counter">
  3. {{ formattedTime }}
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. name: 'TimeClock',
  9. // props 定义(与 Vue3 逻辑一致,保留非负整数校验)
  10. props: {
  11. initialSeconds: {
  12. type: Number,
  13. required: true,
  14. validator(value) {
  15. // 校验:必须是非负整数
  16. return Number.isInteger(value) && value >= 0
  17. }
  18. }
  19. },
  20. data() {
  21. return {
  22. // 当前累计毫秒
  23. currentMillis: Math.floor(this.initialSeconds),
  24. // 定时器实例(用于清理)
  25. timer: null
  26. }
  27. },
  28. computed: {
  29. // 格式化时间:毫秒 → 00:00:00.000 格式
  30. formattedTime() {
  31. const totalMs = this.currentMillis
  32. const hours = String(Math.floor(totalMs / 3600000)).padStart(2, '0')
  33. const minutes = String(Math.floor((totalMs % 3600000) / 60000)).padStart(2, '0')
  34. const seconds = String(Math.floor((totalMs % 60000) / 1000)).padStart(2, '0')
  35. const milliseconds = String(totalMs % 1000).padStart(3, '0')
  36. return `${hours}:${minutes}:${seconds}.${milliseconds}`
  37. }
  38. },
  39. watch: {
  40. // 监听初始秒数变化(对应 Vue3 的 watch 函数)
  41. initialSeconds: {
  42. handler(newVal) {
  43. // 同步为毫秒值并重启计时
  44. const safeVal = Number(newVal)
  45. this.currentMillis = Number.isFinite(safeVal) ? Math.floor(safeVal) : 0
  46. this.startTimer() // 重启定时器
  47. },
  48. immediate: true
  49. }
  50. },
  51. methods: {
  52. // 启动计时(毫秒级递增)
  53. startTimer() {
  54. // 清除已有定时器,避免重复计时
  55. if (this.timer) clearInterval(this.timer)
  56. // 每 10ms 递增 10 毫秒(兼顾性能与精度)
  57. const step = 10
  58. this.timer = setInterval(() => {
  59. this.currentMillis += step
  60. }, step)
  61. }
  62. },
  63. // 初始化时启动计时(对应 Vue3 的 setup 初始化逻辑)
  64. mounted() {
  65. this.startTimer()
  66. },
  67. // 组件卸载时清理定时器(避免内存泄漏,与 Vue3 一致)
  68. beforeDestroy() {
  69. if (this.timer) clearInterval(this.timer)
  70. }
  71. }
  72. </script>
  73. <style scoped>
  74. .time-counter {
  75. font-size: 14px;
  76. font-weight: 600;
  77. color: #ff0000;
  78. letter-spacing: 2px;
  79. }
  80. </style>