vue实现简易时钟
使用 Vue 实现简易时钟
以下是基于 Vue 3 实现简易时钟的两种方法:
方法一:使用 Composition API
<template>
<div class="clock">
{{ hours }}:{{ minutes }}:{{ seconds }}
</div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
const hours = ref('00')
const minutes = ref('00')
const seconds = ref('00')
let timer = null
const updateTime = () => {
const now = new Date()
hours.value = String(now.getHours()).padStart(2, '0')
minutes.value = String(now.getMinutes()).padStart(2, '0')
seconds.value = String(now.getSeconds()).padStart(2, '0')
}
onMounted(() => {
updateTime()
timer = setInterval(updateTime, 1000)
})
onBeforeUnmount(() => {
clearInterval(timer)
})
</script>
<style>
.clock {
font-size: 2rem;
font-family: monospace;
}
</style>
方法二:使用 Options API
<template>
<div class="clock">
{{ time }}
</div>
</template>
<script>
export default {
data() {
return {
time: '00:00:00',
timer: null
}
},
methods: {
updateTime() {
const now = new Date()
this.time = [
String(now.getHours()).padStart(2, '0'),
String(now.getMinutes()).padStart(2, '0'),
String(now.getSeconds()).padStart(2, '0')
].join(':')
}
},
mounted() {
this.updateTime()
this.timer = setInterval(this.updateTime, 1000)
},
beforeUnmount() {
clearInterval(this.timer)
}
}
</script>
<style>
.clock {
font-size: 2rem;
font-family: monospace;
}
</style>
关键点说明
- 使用
setInterval每秒更新一次时间 - 使用
padStart(2, '0')确保数字始终显示两位数 - 组件卸载时清除定时器防止内存泄漏
- 两种实现方式分别展示了 Vue 3 的 Composition API 和传统的 Options API
扩展功能
如需添加日期显示,可以在模板中添加:
<div class="date">
{{ year }}-{{ month }}-{{ day }}
</div>
并在 JavaScript 中添加相应的数据属性和更新逻辑:
// Composition API 示例
const year = ref('')
const month = ref('')
const day = ref('')
const updateDate = () => {
const now = new Date()
year.value = now.getFullYear()
month.value = String(now.getMonth() + 1).padStart(2, '0')
day.value = String(now.getDate()).padStart(2, '0')
}
样式优化
可以添加 CSS 动画使时钟更生动:
.clock {
transition: color 0.5s ease;
}
.clock:hover {
color: #42b983;
}





