vue实现翻牌效果案例
Vue 实现翻牌效果案例
翻牌效果通常用于展示卡片翻转动画,常见于记忆游戏或展示正反面内容。以下是基于 Vue 3 的实现方案:
基础翻牌效果实现
创建翻转动画的核心是利用 CSS 的 transform 和 transition 属性,结合 Vue 的动态类名控制。
<template>
<div class="flip-container" @click="isFlipped = !isFlipped">
<div class="flipper" :class="{ flipped: isFlipped }">
<div class="front">
<!-- 正面内容 -->
Click to Flip
</div>
<div class="back">
<!-- 背面内容 -->
Back Content
</div>
</div>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const isFlipped = ref(false)
return { isFlipped }
}
}
</script>
<style scoped>
.flip-container {
perspective: 1000px;
width: 200px;
height: 200px;
}
.flipper {
position: relative;
width: 100%;
height: 100%;
transition: transform 0.6s;
transform-style: preserve-3d;
}
.front, .back {
position: absolute;
width: 100%;
height: 100%;
backface-visibility: hidden;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #ccc;
border-radius: 8px;
}
.front {
background: #f0f0f0;
}
.back {
background: #e0e0e0;
transform: rotateY(180deg);
}
.flipped {
transform: rotateY(180deg);
}
</style>
3D 翻牌增强效果
添加阴影和深度感可增强 3D 效果:
.flip-container {
perspective: 1000px;
width: 200px;
height: 200px;
margin: 20px;
}
.flipper {
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
border-radius: 8px;
}
动态内容翻牌
通过 props 传递正反面内容实现组件复用:
<template>
<FlipCard :frontText="'Front'" :backText="'Back'" />
</template>
<!-- FlipCard.vue -->
<script>
export default {
props: {
frontText: String,
backText: String
}
}
</script>
自动翻转功能
添加定时器实现自动翻转效果:
import { onMounted, onUnmounted } from 'vue'
export default {
setup() {
const isFlipped = ref(false)
let timer
onMounted(() => {
timer = setInterval(() => {
isFlipped.value = !isFlipped.value
}, 2000)
})
onUnmounted(() => {
clearInterval(timer)
})
return { isFlipped }
}
}
性能优化建议
对于多卡片场景,使用 will-change 属性提升动画性能:
.flipper {
will-change: transform;
}
移动端适配
添加触摸事件支持:
<div
class="flip-container"
@click="toggleFlip"
@touchstart="toggleFlip"
></div>
这些实现方案可根据具体需求组合使用,通过调整 CSS 过渡时间和 3D 透视参数可获得不同的视觉效果。







