vue2实现翻书
Vue2 实现翻书效果
翻书效果可以通过 CSS 动画和 Vue 的数据绑定实现。以下是一个基于 Vue2 的翻书效果实现方法。
基本结构
创建 Vue 实例并定义数据,包括当前页码和总页数。
new Vue({
el: '#app',
data: {
currentPage: 1,
totalPages: 5,
isTurning: false
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages && !this.isTurning) {
this.isTurning = true;
this.currentPage++;
setTimeout(() => {
this.isTurning = false;
}, 1000);
}
},
prevPage() {
if (this.currentPage > 1 && !this.isTurning) {
this.isTurning = true;
this.currentPage--;
setTimeout(() => {
this.isTurning = false;
}, 1000);
}
}
}
});
HTML 结构
使用 Vue 绑定数据,并添加翻页按钮。
<div id="app">
<div class="book">
<div
class="page"
v-for="page in totalPages"
:key="page"
:class="{ 'active': page === currentPage, 'turning': isTurning && page === currentPage }"
>
Page {{ page }}
</div>
</div>
<button @click="prevPage" :disabled="currentPage === 1 || isTurning">Previous</button>
<button @click="nextPage" :disabled="currentPage === totalPages || isTurning">Next</button>
</div>
CSS 样式
添加翻书动画效果。
.book {
perspective: 1000px;
width: 300px;
height: 400px;
position: relative;
margin: 20px auto;
}
.page {
width: 100%;
height: 100%;
position: absolute;
background: #fff;
border: 1px solid #ccc;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
transform-origin: left;
transform-style: preserve-3d;
transition: transform 1s;
}
.page.active {
z-index: 1;
}
.page.turning {
transform: rotateY(-180deg);
}
button {
margin: 10px;
padding: 8px 16px;
cursor: pointer;
}
button:disabled {
cursor: not-allowed;
opacity: 0.5;
}
实现原理
- 通过 Vue 的
v-for渲染多个页面。 - 使用 CSS 的
transform和transition实现翻页动画。 - 通过
isTurning控制动画状态,防止快速点击导致动画混乱。
扩展功能
如果需要更复杂的翻书效果,可以引入第三方库如 turn.js 或 flipbook-vue,这些库提供了更丰富的翻页动画和交互功能。
// 使用 turn.js 示例
import 'turn.js';
注意事项
- 确保浏览器支持 CSS 3D 变换。
- 动画时间可以根据实际需求调整。
- 对于移动端,可能需要添加触摸事件支持。



