vue 实现时钟
使用 Vue 实现时钟的步骤
基础实现:显示当前时间
通过 Date 对象获取当前时间,并使用 setInterval 动态更新数据。
<template>
<div>{{ currentTime }}</div>
</template>
<script>
export default {
data() {
return {
currentTime: ''
}
},
mounted() {
this.updateTime();
setInterval(this.updateTime, 1000);
},
methods: {
updateTime() {
const now = new Date();
this.currentTime = now.toLocaleTimeString();
}
}
}
</script>
格式化时间显示
自定义时间格式(如 HH:MM:SS),通过方法手动拼接字符串。
methods: {
formatTime(date) {
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
return `${hours}:${minutes}:${seconds}`;
},
updateTime() {
this.currentTime = this.formatTime(new Date());
}
}
添加日期显示
扩展功能,同时显示日期和星期。
methods: {
formatDate(date) {
const days = ['日', '一', '二', '三', '四', '五', '六'];
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const week = days[date.getDay()];
return `${year}-${month}-${day} 星期${week}`;
},
updateTime() {
const now = new Date();
this.currentDate = this.formatDate(now);
this.currentTime = this.formatTime(now);
}
}
使用计算属性优化
将时间格式化逻辑移至计算属性,减少方法调用。
computed: {
currentTime() {
const now = new Date();
return this.formatTime(now);
},
currentDate() {
const now = new Date();
return this.formatDate(now);
}
}
动态样式与动画
添加 CSS 过渡效果,增强视觉体验。
<template>
<div class="clock">
<div class="time">{{ currentTime }}</div>
<div class="date">{{ currentDate }}</div>
</div>
</template>
<style>
.clock {
font-family: monospace;
text-align: center;
}
.time {
font-size: 3em;
transition: color 0.5s;
}
.date {
font-size: 1.5em;
opacity: 0.8;
}
</style>
使用第三方库(可选)
对于复杂需求(如时区处理),可引入 moment.js 或 day.js。
import dayjs from 'dayjs';
methods: {
updateTime() {
this.currentTime = dayjs().format('HH:mm:ss');
this.currentDate = dayjs().format('YYYY-MM-DD dddd');
}
}
注意事项
- 组件销毁时需清除定时器,避免内存泄漏。
- 服务端渲染(SSR)场景需兼容
mounted生命周期。 - 移动端可添加
@touchstart事件唤醒屏幕常亮功能。







