vue实现商品秒杀
Vue 实现商品秒杀功能
前端页面设计
使用 Vue 的组件化开发方式,构建秒杀商品展示页面。通过 v-for 循环渲染商品列表,展示商品图片、名称、原价、秒杀价和倒计时。

<template>
<div class="seckill-container">
<div v-for="item in seckillList" :key="item.id" class="seckill-item">
<img :src="item.image" alt="商品图片">
<h3>{{ item.name }}</h3>
<p class="original-price">原价: ¥{{ item.originalPrice }}</p>
<p class="seckill-price">秒杀价: ¥{{ item.seckillPrice }}</p>
<count-down :end-time="item.endTime" @time-up="handleTimeUp(item.id)"></count-down>
<button @click="handleSeckill(item.id)" :disabled="item.isDisabled">立即秒杀</button>
</div>
</div>
</template>
倒计时组件
创建一个独立的倒计时组件,实时显示剩余时间,并在时间结束时触发回调。

// CountDown.vue
export default {
props: ['endTime'],
data() {
return {
remainingTime: 0
}
},
mounted() {
this.updateRemainingTime()
this.timer = setInterval(this.updateRemainingTime, 1000)
},
methods: {
updateRemainingTime() {
const now = new Date().getTime()
this.remainingTime = Math.max(0, this.endTime - now)
if (this.remainingTime <= 0) {
clearInterval(this.timer)
this.$emit('time-up')
}
}
},
computed: {
formattedTime() {
const hours = Math.floor(this.remainingTime / (1000 * 60 * 60))
const minutes = Math.floor((this.remainingTime % (1000 * 60 * 60)) / (1000 * 60))
const seconds = Math.floor((this.remainingTime % (1000 * 60)) / 1000)
return `${hours}:${minutes}:${seconds}`
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
秒杀逻辑实现
在前端实现基本的防重复提交和状态管理,通过 API 与后端交互。
export default {
data() {
return {
seckillList: [],
isSubmitting: false
}
},
created() {
this.fetchSeckillList()
},
methods: {
async fetchSeckillList() {
const response = await axios.get('/api/seckill/list')
this.seckillList = response.data.map(item => ({
...item,
isDisabled: false
}))
},
async handleSeckill(productId) {
if (this.isSubmitting) return
this.isSubmitting = true
try {
const response = await axios.post('/api/seckill/buy', { productId })
if (response.data.success) {
this.$message.success('秒杀成功!')
this.updateProductStatus(productId)
} else {
this.$message.error(response.data.message)
}
} catch (error) {
this.$message.error('网络错误,请重试')
} finally {
this.isSubmitting = false
}
},
updateProductStatus(productId) {
const product = this.seckillList.find(item => item.id === productId)
if (product) {
product.isDisabled = true
}
},
handleTimeUp(productId) {
const product = this.seckillList.find(item => item.id === productId)
if (product) {
product.isDisabled = true
}
}
}
}
后端接口注意事项
前端需要与后端配合实现完整的秒杀功能,后端应处理以下关键点:
- 使用 Redis 缓存秒杀商品库存,避免频繁访问数据库
- 实现分布式锁防止超卖
- 使用消息队列处理高并发请求
- 验证用户身份和请求频率
性能优化建议
- 使用 CDN 加速静态资源加载
- 实现前端限流,防止用户频繁点击
- 添加加载状态和错误处理
- 使用 WebSocket 实时更新库存信息
安全防护措施
- 添加验证码防止机器人刷单
- 实现接口签名验证
- 限制同一用户的购买次数
- 隐藏真实的接口地址
以上实现方案结合了 Vue 的前端优势和秒杀场景的特殊需求,可根据实际项目情况进行调整和扩展。






