vue实现共享动画
Vue 共享动画实现方法
使用 Vue Transition 组件
Vue 内置的 Transition 组件可以实现元素进入/离开的过渡效果。通过命名过渡和 mode 属性可以控制多个元素的过渡顺序。
<transition name="fade" mode="out-in">
<component :is="currentComponent"></component>
</transition>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
使用 Vue Router 过渡
在路由切换时实现页面间的共享动画效果,可以在 router-view 外包裹 Transition 组件。
<router-view v-slot="{ Component }">
<transition name="slide" mode="out-in">
<component :is="Component" />
</transition>
</router-view>
使用 FLIP 动画技术
FLIP (First, Last, Invert, Play) 技术可以实现高性能的共享元素过渡。
function flipAnimation(el, newRect, duration = 300) {
const oldRect = el.getBoundingClientRect()
const dx = oldRect.left - newRect.left
const dy = oldRect.top - newRect.top
const dw = oldRect.width / newRect.width
const dh = oldRect.height / newRect.height
el.style.transform = `translate(${dx}px, ${dy}px) scale(${dw}, ${dh})`
el.style.transition = 'transform 0s'
requestAnimationFrame(() => {
el.style.transform = ''
el.style.transition = `transform ${duration}ms`
})
}
使用第三方库
Vue 生态中有多个专门处理动画的库:
- VueUse 的 useTransition 组合式 API
- Vue-Kinesis 提供物理动画效果
- GSAP 与 Vue 结合使用
import { gsap } from 'gsap'
export default {
methods: {
animateElement(el) {
gsap.from(el, {
duration: 0.5,
opacity: 0,
y: 20,
ease: 'power2.out'
})
}
}
}
状态驱动的动画
通过 Vue 的响应式系统和计算属性,可以实现基于状态变化的动画。
const app = Vue.createApp({
data() {
return {
progress: 0
}
},
computed: {
progressStyle() {
return {
width: `${this.progress}%`,
transition: 'width 0.5s ease'
}
}
}
})
组件间通信动画
通过事件总线或状态管理实现跨组件的动画协调。
// 在共享状态中
const store = {
state: {
activeElement: null
},
setActiveElement(id) {
this.state.activeElement = id
}
}
// 在组件中
watch(() => store.state.activeElement, (newVal, oldVal) => {
if (this.id === newVal || this.id === oldVal) {
this.animate()
}
})
性能优化技巧
- 使用 will-change 属性提示浏览器
- 优先使用 transform 和 opacity 属性
- 减少动画期间的 DOM 操作
- 合理使用 requestAnimationFrame
.animated-element {
will-change: transform, opacity;
}






