当前位置:首页 > VUE

vue 实现跳转动画

2026-01-22 01:54:58VUE

Vue 路由跳转动画实现

在 Vue 中实现页面跳转动画可以通过 Vue Router 的过渡效果和 CSS 动画结合完成。以下是几种常见方法:

使用 Vue Transition 组件

在 App.vue 或布局组件中包裹 <router-view>,并添加过渡效果:

<template>
  <router-view v-slot="{ Component }">
    <transition name="fade" mode="out-in">
      <component :is="Component" />
    </transition>
  </router-view>
</template>

<style>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>

实现滑动动画

通过 CSS transform 属性实现左右滑动效果:

vue 实现跳转动画

.slide-left-enter-active,
.slide-left-leave-active,
.slide-right-enter-active,
.slide-right-leave-active {
  transition: all 0.5s ease;
}

.slide-left-enter-from {
  transform: translateX(100%);
}

.slide-left-leave-to {
  transform: translateX(-100%);
}

.slide-right-enter-from {
  transform: translateX(-100%);
}

.slide-right-leave-to {
  transform: translateX(100%);
}

动态过渡名称

根据路由变化方向应用不同动画:

<script setup>
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const transitionName = ref('slide-left')

watch(router.currentRoute, (to, from) => {
  const toDepth = to.meta.depth || 0
  const fromDepth = from.meta.depth || 0
  transitionName.value = toDepth > fromDepth ? 'slide-left' : 'slide-right'
})
</script>

<template>
  <router-view v-slot="{ Component }">
    <transition :name="transitionName">
      <component :is="Component" />
    </transition>
  </router-view>
</template>

使用 GSAP 实现高级动画

安装 GSAP 库实现更复杂的动画效果:

vue 实现跳转动画

npm install gsap

在路由守卫中使用 GSAP:

import { gsap } from 'gsap'

router.beforeEach((to, from, next) => {
  gsap.to('.page-container', {
    duration: 0.5,
    opacity: 0,
    y: 50,
    onComplete: next
  })
})

router.afterEach(() => {
  gsap.from('.page-container', {
    duration: 0.5,
    opacity: 0,
    y: -50
  })
})

页面单独控制动画

在页面组件中定义进入和离开动画:

<script>
export default {
  beforeRouteLeave(to, from, next) {
    this.animateOut(() => next())
  },
  methods: {
    animateOut(callback) {
      // 自定义离开动画逻辑
      callback()
    }
  }
}
</script>

注意事项

  • 使用 mode="out-in" 确保当前元素先完成离开动画,新元素再进入
  • 避免在移动设备上使用性能开销大的动画
  • 考虑添加 will-change 属性优化动画性能
  • 测试不同路由跳转场景确保动画连贯性

标签: 跳转动画
分享给朋友:

相关文章

vue实现前端跳转

vue实现前端跳转

Vue 实现前端跳转的方法 在 Vue 中实现前端跳转通常使用 Vue Router,以下是几种常见的跳转方式: 声明式导航(模板中使用 <router-link>) 在模板中直接使用…

php实现页面跳转

php实现页面跳转

PHP实现页面跳转的方法 在PHP中,可以通过多种方式实现页面跳转,以下是几种常用的方法: header函数跳转 header("Location: target_page.php"); exit…

js实现页面跳转

js实现页面跳转

使用 window.location.href 通过修改 window.location.href 实现页面跳转,直接赋值目标 URL 即可。 window.location.href = 'h…

vue的动画实现

vue的动画实现

Vue 动画实现方式 Vue 提供了多种方式实现动画效果,主要包括内置组件和第三方库。 使用 <transition> 和 <transition-group> Vue 内置…

vue实现点击跳转路由

vue实现点击跳转路由

vue实现点击跳转路由的方法 在Vue中实现点击跳转路由,可以通过以下几种方式完成,具体取决于项目使用的路由管理工具(如Vue Router)以及需求场景。 使用router-link组件 rou…

js实现动画

js实现动画

使用 CSS 动画与 JavaScript 控制 通过 JavaScript 动态添加或移除 CSS 类来触发动画。CSS 定义关键帧(@keyframes),JavaScript 通过 classL…