vue实现倒计时抢券
实现思路
通过 Vue 的响应式数据绑定和定时器功能,结合计算属性动态展示倒计时剩余时间,并在倒计时结束后触发抢券逻辑。
核心代码实现
<template>
<div>
<button @click="startCountdown" :disabled="isDisabled">
{{ buttonText }}
</button>
<p v-if="timeLeft > 0">剩余时间: {{ formattedTime }}</p>
</div>
</template>
<script>
export default {
data() {
return {
timeLeft: 10, // 倒计时总秒数(示例为10秒)
timer: null,
isCounting: false
};
},
computed: {
formattedTime() {
const minutes = Math.floor(this.timeLeft / 60);
const seconds = this.timeLeft % 60;
return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
},
isDisabled() {
return this.timeLeft > 0 || this.isCounting;
},
buttonText() {
return this.timeLeft > 0 ? '抢券倒计时' : '立即抢券';
}
},
methods: {
startCountdown() {
if (this.timeLeft <= 0) {
this.handleGrabCoupon();
return;
}
this.isCounting = true;
this.timer = setInterval(() => {
this.timeLeft--;
if (this.timeLeft <= 0) {
clearInterval(this.timer);
this.isCounting = false;
}
}, 1000);
},
handleGrabCoupon() {
// 实际抢券逻辑(如调用API)
alert('抢券成功!');
}
},
beforeDestroy() {
clearInterval(this.timer); // 清除定时器避免内存泄漏
}
};
</script>
关键点说明
- 定时器管理:通过
setInterval实现倒计时,组件销毁时需清除定时器。 - 响应式更新:利用
computed动态计算剩余时间的格式化显示(分钟:秒)。 - 状态控制:
isDisabled控制按钮禁用状态,避免重复触发。
优化方向
- 本地存储恢复:通过
localStorage保存倒计时状态,刷新页面后继续倒计时。 - 服务端同步:从接口获取剩余时间,避免客户端时间误差。
- 动画效果:添加 CSS 动画增强交互体验。
完整示例扩展
// 本地存储恢复示例
created() {
const savedTime = localStorage.getItem('couponTime');
if (savedTime && savedTime > 0) {
this.timeLeft = savedTime;
this.startCountdown();
}
},
watch: {
timeLeft(newVal) {
localStorage.setItem('couponTime', newVal);
}
}






