vue 实现切屏动画
实现基础切屏动画
使用 Vue 的 <transition> 组件包裹需要切换的元素,结合 CSS 过渡类名实现动画效果。通过 name 属性定义动画前缀,例如 name="fade" 会生成 .fade-enter-active 等类名。
<transition name="fade">
<div v-if="show" key="content">内容区域</div>
</transition>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
使用动态组件切换
结合 <component :is="currentComponent"> 实现组件级切屏动画,适用于多页面切换场景。每个组件需要设置唯一的 key 以保证过渡效果触发。
<transition name="slide" mode="out-in">
<component :is="currentView" :key="currentView"></component>
</transition>
.slide-enter-active {
animation: slideIn 0.3s;
}
.slide-leave-active {
animation: slideOut 0.3s;
}
@keyframes slideIn {
from { transform: translateX(100%); }
to { transform: translateX(0); }
}
@keyframes slideOut {
from { transform: translateX(0); }
to { transform: translateX(-100%); }
}
路由切换动画
在 Vue Router 中使用 <router-view> 实现页面路由切换动画,通过路由元信息控制不同过渡效果。
<transition :name="transitionName">
<router-view></router-view>
</transition>
watch: {
'$route'(to, from) {
this.transitionName = to.meta.transition || 'fade'
}
}
使用第三方动画库
集成 animate.css 等动画库快速实现专业效果,通过自定义过渡类名直接应用预设动画。
<transition
enter-active-class="animate__animated animate__fadeInLeft"
leave-active-class="animate__animated animate__fadeOutRight"
>
<div v-if="show">动画内容</div>
</transition>
手势驱动动画
通过 Hammer.js 等库实现手势滑动切屏,结合 Vue 的响应式数据控制动画状态。
import Hammer from 'hammerjs'
mounted() {
const hammer = new Hammer(this.$el)
hammer.on('swipeleft', () => {
this.currentIndex = Math.min(this.currentIndex + 1, this.maxIndex)
})
hammer.on('swiperight', () => {
this.currentIndex = Math.max(this.currentIndex - 1, 0)
})
}
性能优化建议
对移动端设备启用硬件加速,使用 will-change 和 transform 属性提升动画流畅度。避免同时触发过多属性变化,优先使用 opacity 和 transform 进行动画处理。
.optimized-animation {
will-change: transform, opacity;
transform: translateZ(0);
}






