time-clock.vue 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. // 当前累计秒数(对应 Vue3 的 ref 响应式变量)
  23. currentSeconds: this.initialSeconds,
  24. // 定时器实例(用于清理)
  25. timer: null
  26. }
  27. },
  28. computed: {
  29. // 格式化时间:秒数 → 00:00:00 格式(逻辑与 Vue3 完全一致)
  30. formattedTime() {
  31. const hours = String(Math.floor(this.currentSeconds / 3600)).padStart(2, '0')
  32. const minutes = String(Math.floor((this.currentSeconds % 3600) / 60)).padStart(2, '0')
  33. const seconds = String(this.currentSeconds % 60).padStart(2, '0')
  34. return `${hours}:${minutes}:${seconds}`
  35. }
  36. },
  37. watch: {
  38. // 监听初始秒数变化(对应 Vue3 的 watch 函数)
  39. initialSeconds: {
  40. handler(newVal) {
  41. this.currentSeconds = newVal // 更新当前秒数为新初始值
  42. this.startTimer() // 重启定时器
  43. },
  44. immediate: true
  45. }
  46. },
  47. methods: {
  48. // 启动计时(逻辑与 Vue3 一致)
  49. startTimer() {
  50. // 清除已有定时器,避免重复计时
  51. if (this.timer) clearInterval(this.timer)
  52. // 每秒递增 1 秒
  53. this.timer = setInterval(() => {
  54. this.currentSeconds += 1
  55. }, 1000)
  56. }
  57. },
  58. // 初始化时启动计时(对应 Vue3 的 setup 初始化逻辑)
  59. mounted() {
  60. this.startTimer()
  61. },
  62. // 组件卸载时清理定时器(避免内存泄漏,与 Vue3 一致)
  63. beforeDestroy() {
  64. if (this.timer) clearInterval(this.timer)
  65. }
  66. }
  67. </script>
  68. <style scoped>
  69. .time-counter {
  70. font-size: 13px;
  71. font-weight: 500;
  72. color: #ff0000;
  73. letter-spacing: 2px;
  74. font-family: 'Arial', sans-serif;
  75. /* 确保数字显示整齐 */
  76. }
  77. </style>