vue实现翻牌抽奖
Vue 实现翻牌抽奖功能
翻牌抽奖是一种常见的互动效果,可以通过 Vue 结合 CSS 动画实现。以下是具体实现方法:
数据结构与基本布局
使用 Vue 的 data 定义奖品列表和当前翻牌状态:
data() {
return {
prizes: [
{ id: 1, name: '奖品1', flipped: false },
{ id: 2, name: '奖品2', flipped: false },
// 更多奖品...
],
isDrawing: false
}
}
模板部分使用 v-for 渲染奖品卡片:
<div class="card-container">
<div
v-for="(prize, index) in prizes"
:key="prize.id"
:class="['card', { 'flipped': prize.flipped }]"
@click="flipCard(index)"
>
<div class="card-front">点击抽奖</div>
<div class="card-back">{{ prize.name }}</div>
</div>
</div>
CSS 动画样式
实现卡片翻转的 3D 效果:

.card-container {
display: flex;
flex-wrap: wrap;
perspective: 1000px;
}
.card {
width: 100px;
height: 150px;
margin: 10px;
position: relative;
transform-style: preserve-3d;
transition: transform 0.6s;
}
.card-front, .card-back {
position: absolute;
width: 100%;
height: 100%;
backface-visibility: hidden;
display: flex;
align-items: center;
justify-content: center;
border-radius: 8px;
}
.card-front {
background: #3498db;
color: white;
}
.card-back {
background: #e74c3c;
color: white;
transform: rotateY(180deg);
}
.card.flipped {
transform: rotateY(180deg);
}
抽奖逻辑实现
在 methods 中实现翻牌和抽奖逻辑:
methods: {
flipCard(index) {
if (this.isDrawing) return;
this.isDrawing = true;
this.prizes[index].flipped = true;
// 模拟抽奖结果
setTimeout(() => {
const resultIndex = Math.floor(Math.random() * this.prizes.length);
this.prizes.forEach((p, i) => {
p.flipped = i === resultIndex;
});
this.isDrawing = false;
}, 1000);
}
}
高级优化方案
对于更复杂的需求,可以考虑以下优化:

添加抽奖次数限制
data() {
return {
drawCount: 0,
maxDrawCount: 3
}
}
methods: {
flipCard(index) {
if (this.isDrawing || this.drawCount >= this.maxDrawCount) return;
// ...原有逻辑
this.drawCount++;
}
}
实现批量翻牌动画效果
async batchFlip() {
this.isDrawing = true;
for (let i = 0; i < this.prizes.length; i++) {
await new Promise(resolve => {
setTimeout(() => {
this.prizes[i].flipped = true;
resolve();
}, 200 * i);
});
}
setTimeout(() => {
this.resetCards();
this.isDrawing = false;
}, 1000);
}
移动端适配
添加触摸事件支持:
<div
@touchstart="handleTouchStart"
@touchend="handleTouchEnd"
>
<!-- 卡片内容 -->
</div>
methods: {
handleTouchStart(e) {
this.touchStartX = e.touches[0].clientX;
},
handleTouchEnd(e) {
const touchEndX = e.changedTouches[0].clientX;
if (Math.abs(touchEndX - this.touchStartX) < 10) {
this.flipCard();
}
}
}






