在vue2框架下写一个倒计时组件
时间: 2023-11-06 19:08:01 浏览: 72
可以参考以下代码实现一个简单的倒计时组件:
```
<template>
<div class="countdown">
<span>{{ days }}</span>天
<span>{{ hours }}</span>小时
<span>{{ minutes }}</span>分钟
<span>{{ seconds }}</span>秒
</div>
</template>
<script>
export default {
name: 'Countdown',
props: {
endTime: {
type: Number,
required: true
}
},
data() {
return {
days: 0,
hours: 0,
minutes: 0,
seconds: 0
}
},
mounted() {
this.timer = setInterval(() => {
const now = Date.now();
const distance = this.endTime - now;
if (distance <= 0) {
clearInterval(this.timer);
return;
}
this.days = Math.floor(distance / (1000 * 60 * 60 * 24));
this.hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
this.minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
this.seconds = Math.floor((distance % (1000 * 60)) / 1000);
}, 1000);
},
beforeDestroy() {
clearInterval(this.timer);
}
}
</script>
<style scoped>
.countdown {
font-size: 1.2em;
text-align: center;
}
</style>
```
使用时,只需要传入一个结束时间戳 `endTime`,就可以自动计算出距离结束时间还剩下多少天、小时、分钟和秒数,并且自动更新倒计时。例如:
```
<Countdown :endTime="new Date('2022-01-01').getTime()"></Countdown>
```
阅读全文