| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <template>
- <div class="time-counter">
- {{ formattedTime }}
- </div>
- </template>
- <script>
- export default {
- name: 'TimeClock',
- // props 定义(与 Vue3 逻辑一致,保留非负整数校验)
- props: {
- initialSeconds: {
- type: Number,
- required: true,
- validator(value) {
- // 校验:必须是非负整数
- return Number.isInteger(value) && value >= 0
- }
- }
- },
- data() {
- return {
- // 当前累计毫秒
- currentMillis: Math.floor(this.initialSeconds),
- // 定时器实例(用于清理)
- timer: null
- }
- },
- computed: {
- // 格式化时间:毫秒 → 00:00:00.000 格式
- formattedTime() {
- const totalMs = this.currentMillis
- const hours = String(Math.floor(totalMs / 3600000)).padStart(2, '0')
- const minutes = String(Math.floor((totalMs % 3600000) / 60000)).padStart(2, '0')
- const seconds = String(Math.floor((totalMs % 60000) / 1000)).padStart(2, '0')
- const milliseconds = String(totalMs % 1000).padStart(3, '0')
- return `${hours}:${minutes}:${seconds}.${milliseconds}`
- }
- },
- watch: {
- // 监听初始秒数变化(对应 Vue3 的 watch 函数)
- initialSeconds: {
- handler(newVal) {
- // 同步为毫秒值并重启计时
- const safeVal = Number(newVal)
- this.currentMillis = Number.isFinite(safeVal) ? Math.floor(safeVal) : 0
- this.startTimer() // 重启定时器
- },
- immediate: true
- }
- },
- methods: {
- // 启动计时(毫秒级递增)
- startTimer() {
- // 清除已有定时器,避免重复计时
- if (this.timer) clearInterval(this.timer)
- // 每 10ms 递增 10 毫秒(兼顾性能与精度)
- const step = 10
- this.timer = setInterval(() => {
- this.currentMillis += step
- }, step)
- }
- },
- // 初始化时启动计时(对应 Vue3 的 setup 初始化逻辑)
- mounted() {
- this.startTimer()
- },
- // 组件卸载时清理定时器(避免内存泄漏,与 Vue3 一致)
- beforeDestroy() {
- if (this.timer) clearInterval(this.timer)
- }
- }
- </script>
- <style scoped>
- .time-counter {
- font-size: 14px;
- font-weight: 600;
- color: #ff0000;
- letter-spacing: 2px;
- }
- </style>
|