vue实现倒计时抢券
Vue 实现倒计时抢券功能
核心逻辑
倒计时功能基于计算剩余时间并动态更新显示,通过 setInterval 实现每秒刷新。抢券按钮状态根据倒计时是否结束进行切换。
实现步骤
数据定义
data() {
return {
countdown: 60, // 初始倒计时60秒
isDisabled: true, // 按钮默认禁用
timer: null // 存储定时器
}
}
倒计时方法
methods: {
startCountdown() {
this.timer = setInterval(() => {
if (this.countdown > 0) {
this.countdown--
} else {
clearInterval(this.timer)
this.isDisabled = false // 倒计时结束启用按钮
}
}, 1000)
},
grabCoupon() {
alert('抢券成功!')
// 实际业务中替换为API调用
}
}
生命周期处理
mounted() {
this.startCountdown()
},
beforeDestroy() {
clearInterval(this.timer) // 组件销毁时清除定时器
}
模板部分
<template>
<div>
<p v-if="isDisabled">倒计时剩余: {{countdown}}秒</p>
<button
:disabled="isDisabled"
@click="grabCoupon">
{{ isDisabled ? '抢券倒计时中' : '立即抢券' }}
</button>
</div>
</template>
优化建议
格式化时间显示 对于超过60秒的倒计时,可以格式化为分钟+秒:
formatTime(seconds) {
const mins = Math.floor(seconds / 60)
const secs = seconds % 60
return `${mins}分${secs}秒`
}
持久化倒计时
使用 localStorage 保持倒计时状态,防止页面刷新重置:
// 读取保存的时间
created() {
const savedTime = localStorage.getItem('countdown')
if (savedTime) {
this.countdown = parseInt(savedTime)
}
}
// 在定时器中添加保存
this.timer = setInterval(() => {
if (this.countdown > 0) {
this.countdown--
localStorage.setItem('countdown', this.countdown)
} else {
localStorage.removeItem('countdown')
// ...原有逻辑
}
}, 1000)
注意事项
- 定时器需在组件销毁时清除,避免内存泄漏
- 服务端时间同步更精确,建议初始化时从接口获取服务器时间
- 移动端需要考虑锁屏状态下的时间误差问题







