vue实现倒计时抢券
实现倒计时抢券功能
在Vue中实现倒计时抢券功能需要结合计时器、状态管理和UI交互。以下是具体实现方法:
核心逻辑实现
使用setInterval创建计时器,在组件销毁时清除避免内存泄漏
data() {
return {
countdown: 60, // 倒计时秒数
timer: null,
isDisabled: true // 按钮禁用状态
}
},
methods: {
startCountdown() {
this.timer = setInterval(() => {
if(this.countdown <= 0) {
clearInterval(this.timer)
this.isDisabled = false
return
}
this.countdown--
}, 1000)
}
},
mounted() {
this.startCountdown()
},
beforeDestroy() {
clearInterval(this.timer)
}
界面显示处理
使用计算属性格式化显示时间

computed: {
formattedTime() {
const minutes = Math.floor(this.countdown / 60)
const seconds = this.countdown % 60
return `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`
}
}
模板部分代码
<template>
<div class="coupon-container">
<div class="countdown">剩余时间: {{ formattedTime }}</div>
<button
:disabled="isDisabled"
@click="handleGrabCoupon"
:class="{ 'disabled-btn': isDisabled }"
>
{{ isDisabled ? '等待抢券' : '立即抢券' }}
</button>
</div>
</template>
样式优化
添加视觉反馈提升用户体验

.disabled-btn {
background-color: #ccc;
cursor: not-allowed;
}
.coupon-container {
text-align: center;
padding: 20px;
}
.countdown {
font-size: 18px;
color: #f56c6c;
margin-bottom: 15px;
}
抢券逻辑实现
点击事件处理函数
methods: {
handleGrabCoupon() {
if(this.isDisabled) return
// 调用API接口
api.grabCoupon().then(res => {
this.$message.success('抢券成功')
}).catch(err => {
this.$message.error(err.message)
})
}
}
服务器时间同步
解决客户端时间不准问题
async syncServerTime() {
const { serverTimestamp } = await api.getServerTime()
const clientTime = Date.now()
this.timeDiff = serverTimestamp - clientTime
}
完整组件示例
export default {
data() {
return {
countdown: 60,
timer: null,
isDisabled: true,
timeDiff: 0
}
},
computed: {
formattedTime() {
const minutes = Math.floor(this.countdown / 60)
const seconds = this.countdown % 60
return `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`
}
},
methods: {
startCountdown() {
this.timer = setInterval(() => {
if(this.countdown <= 0) {
clearInterval(this.timer)
this.isDisabled = false
return
}
this.countdown--
}, 1000)
},
async handleGrabCoupon() {
if(this.isDisabled) return
try {
const res = await api.grabCoupon()
this.$message.success('抢券成功')
} catch (err) {
this.$message.error(err.message)
}
},
async syncServerTime() {
const { serverTimestamp } = await api.getServerTime()
this.timeDiff = serverTimestamp - Date.now()
}
},
async mounted() {
await this.syncServerTime()
this.startCountdown()
},
beforeDestroy() {
clearInterval(this.timer)
}
}
以上实现包含了倒计时核心逻辑、界面显示、样式优化和服务器时间同步等完整功能,可根据实际需求进行调整。






