| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <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 {
- // 当前累计秒数(对应 Vue3 的 ref 响应式变量)
- currentSeconds: this.initialSeconds,
- // 定时器实例(用于清理)
- timer: null
- }
- },
- computed: {
- // 格式化时间:秒数 → 00:00:00 格式(逻辑与 Vue3 完全一致)
- formattedTime() {
- const hours = String(Math.floor(this.currentSeconds / 3600)).padStart(2, '0')
- const minutes = String(Math.floor((this.currentSeconds % 3600) / 60)).padStart(2, '0')
- const seconds = String(this.currentSeconds % 60).padStart(2, '0')
- return `${hours}:${minutes}:${seconds}`
- }
- },
- watch: {
- // 监听初始秒数变化(对应 Vue3 的 watch 函数)
- initialSeconds: {
- handler(newVal) {
- this.currentSeconds = newVal // 更新当前秒数为新初始值
- this.startTimer() // 重启定时器
- },
- immediate: true
- }
- },
- methods: {
- // 启动计时(逻辑与 Vue3 一致)
- startTimer() {
- // 清除已有定时器,避免重复计时
- if (this.timer) clearInterval(this.timer)
- // 每秒递增 1 秒
- this.timer = setInterval(() => {
- this.currentSeconds += 1
- }, 1000)
- }
- },
- // 初始化时启动计时(对应 Vue3 的 setup 初始化逻辑)
- mounted() {
- this.startTimer()
- },
- // 组件卸载时清理定时器(避免内存泄漏,与 Vue3 一致)
- beforeDestroy() {
- if (this.timer) clearInterval(this.timer)
- }
- }
- </script>
- <style scoped>
- .time-counter {
- font-size: 13px;
- font-weight: 500;
- color: #ff0000;
- letter-spacing: 2px;
- font-family: 'Arial', sans-serif;
- /* 确保数字显示整齐 */
- }
- </style>
|