vue实现翻页时钟
以下是在 Vue 中实现翻页时钟的几种方法,结合动画效果和组件化设计:
使用 CSS 动画和动态数据绑定
通过 Vue 的数据响应式特性结合 CSS 翻转动画实现数字切换效果:
<template>
<div class="flip-clock">
<div class="digit" v-for="(digit, index) in displayTime" :key="index">
<div class="digit-top">{{ digit }}</div>
<div class="digit-bottom">{{ digit }}</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentTime: new Date()
}
},
computed: {
displayTime() {
return this.currentTime.toLocaleTimeString().replace(/:/g, '').split('')
}
},
mounted() {
setInterval(() => {
this.currentTime = new Date()
}, 1000)
}
}
</script>
<style>
.flip-clock {
display: flex;
gap: 10px;
}
.digit {
position: relative;
width: 60px;
height: 100px;
perspective: 1000px;
}
.digit-top, .digit-bottom {
position: absolute;
width: 100%;
height: 50%;
overflow: hidden;
text-align: center;
line-height: 100px;
font-size: 3rem;
background: #333;
color: white;
border-radius: 5px;
}
.digit-top {
top: 0;
transform-origin: bottom;
animation: flipTop 0.5s ease-in;
}
.digit-bottom {
bottom: 0;
}
@keyframes flipTop {
0% { transform: rotateX(0deg); }
100% { transform: rotateX(-90deg); }
}
</style>
使用第三方库
对于更复杂的效果,可以集成专门的动画库:
-
安装 flipclock 库:
npm install flipclock -
组件实现:
<template> <div ref="clock"></div> </template>
export default { mounted() { new FlipClock(this.$refs.clock, new Date(), { face: 'HourCounter', autoStart: true }) } }
```优化性能的版本
通过 requestAnimationFrame 优化动画性能:
methods: {
updateClock() {
this.animationId = requestAnimationFrame(() => {
const now = new Date()
if (now.getSeconds() !== this.currentTime.getSeconds()) {
this.currentTime = now
}
this.updateClock()
})
},
beforeDestroy() {
cancelAnimationFrame(this.animationId)
}
}
组件化设计
将数字卡片拆分为独立组件:
<template>
<FlipDigit :value="hours" />
<span class="separator">:</span>
<FlipDigit :value="minutes" />
<span class="separator">:</span>
<FlipDigit :value="seconds" />
</template>
每个 FlipDigit 组件管理自己的翻转状态,通过 watch 监听值变化触发动画。
关键点在于:
- 使用 CSS 3D 变换实现翻转效果
- 通过 Vue 的响应式系统同步时间变化
- 组件拆分提高可维护性
- 性能优化避免不必要的重绘







