用vue3写一个天时分秒毫秒的倒计时
时间: 2023-11-14 15:53:38 浏览: 76
Vue写一个简单的倒计时按钮功能
5星 · 资源好评率100%
<template>
<div class="countdown">
<div class="countdown-item">
<div class="countdown-value">{{ days }}</div>
<div class="countdown-label">天</div>
</div>
<div class="countdown-item">
<div class="countdown-value">{{ hours }}</div>
<div class="countdown-label">小时</div>
</div>
<div class="countdown-item">
<div class="countdown-value">{{ minutes }}</div>
<div class="countdown-label">分钟</div>
</div>
<div class="countdown-item">
<div class="countdown-value">{{ seconds }}</div>
<div class="countdown-label">秒钟</div>
</div>
<div class="countdown-item">
<div class="countdown-value">{{ milliseconds }}</div>
<div class="countdown-label">毫秒</div>
</div>
</div>
</template>
<script>
import { ref, watch, onMounted } from 'vue'
export default {
setup() {
const days = ref('00')
const hours = ref('00')
const minutes = ref('00')
const seconds = ref('00')
const milliseconds = ref('00')
let intervalId
const startCountdown = (endDate) => {
clearInterval(intervalId)
const now = new Date().getTime()
const distance = endDate - now
if (distance <= 0) {
clearInterval(intervalId)
} else {
const d = Math.floor(distance / (1000 * 60 * 60 * 24))
const h = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
const m = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))
const s = Math.floor((distance % (1000 * 60)) / 1000)
const ms = Math.floor(distance % 1000)
days.value = d < 10 ? `0${d}` : d
hours.value = h < 10 ? `0${h}` : h
minutes.value = m < 10 ? `0${m}` : m
seconds.value = s < 10 ? `0${s}` : s
milliseconds.value = ms < 10 ? `00${ms}` : ms < 100 ? `0${ms}` : ms
}
}
onMounted(() => {
const endDate = new Date('2022/01/01').getTime()
startCountdown(endDate)
intervalId = setInterval(() => {
startCountdown(endDate)
}, 1)
})
return {
days,
hours,
minutes,
seconds,
milliseconds
}
}
}
</script>
<style>
.countdown {
display: flex;
justify-content: center;
align-items: center;
font-size: 2rem;
font-weight: bold;
}
.countdown-item {
display: flex;
flex-direction: column;
align-items: center;
margin: 0 0.5rem;
}
.countdown-label {
font-size: 0.8rem;
font-weight: normal;
}
</style>
阅读全文