vue实现活动倒计时
使用计算属性实现倒计时
在Vue组件中定义活动结束时间,通过计算属性实时计算剩余时间
data() {
return {
endTime: new Date('2023-12-31 23:59:59').getTime()
}
},
computed: {
countdown() {
const now = new Date().getTime()
const distance = this.endTime - now
const days = Math.floor(distance / (1000 * 60 * 60 * 24))
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))
const seconds = Math.floor((distance % (1000 * 60)) / 1000)
return {
days,
hours,
minutes,
seconds,
expired: distance < 0
}
}
}
使用定时器自动更新
在mounted生命周期中设置定时器,每秒更新一次倒计时
mounted() {
this.timer = setInterval(() => {
this.$forceUpdate()
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}
模板显示倒计时
在模板中显示格式化后的倒计时,并处理已过期情况

<template>
<div v-if="!countdown.expired">
剩余时间: {{countdown.days}}天 {{countdown.hours}}小时
{{countdown.minutes}}分 {{countdown.seconds}}秒
</div>
<div v-else>
活动已结束
</div>
</template>
使用第三方库day.js优化
安装day.js处理时间格式更便捷
npm install dayjs
在组件中使用day.js

import dayjs from 'dayjs'
computed: {
formattedTime() {
return dayjs(this.endTime).format('YYYY-MM-DD HH:mm:ss')
}
}
响应式设计考虑
添加CSS样式使倒计时更美观
.countdown {
font-size: 1.5rem;
color: #ff4757;
font-weight: bold;
text-align: center;
padding: 20px;
background: #f1f2f6;
border-radius: 8px;
}
移动端适配
添加viewport meta标签确保移动端正常显示
<meta name="viewport" content="width=device-width, initial-scale=1.0">






