给我写一个vue2的18点下班倒计时
时间: 2024-05-20 11:16:55 浏览: 110
<template>
<div class="countdown">
<div class="countdown-item">
<span>{{ hours }}</span>
<span>小时</span>
</div>
<div class="countdown-item">
<span>{{ minutes }}</span>
<span>分钟</span>
</div>
<div class="countdown-item">
<span>{{ seconds }}</span>
<span>秒钟</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
countdown: null,
hours: 0,
minutes: 0,
seconds: 0,
};
},
mounted() {
this.countdown = setInterval(() => {
const now = new Date();
const target = new Date();
target.setHours(18, 0, 0, 0);
let diff = target - now;
if (diff < 0) {
clearInterval(this.countdown);
return;
}
const hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
const minutes = Math.floor(diff / 1000 / 60);
diff -= minutes * 1000 * 60;
const seconds = Math.floor(diff / 1000);
this.hours = hours < 10 ? `0${hours}` : hours;
this.minutes = minutes < 10 ? `0${minutes}` : minutes;
this.seconds = seconds < 10 ? `0${seconds}` : seconds;
}, 1000);
},
beforeDestroy() {
clearInterval(this.countdown);
},
};
</script>
<style scoped>
.countdown {
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
font-weight: bold;
}
.countdown-item {
display: flex;
flex-direction: column;
align-items: center;
margin: 0 10px;
}
.countdown-item span:first-child {
font-size: 48px;
}
.countdown-item span:last-child {
font-size: 18px;
}
</style>
阅读全文