You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3/Nuxt3中如何根据来源页面切换过渡动画?

根据来源页面动态切换Nuxt3/Vue3首页过渡效果

方案一:通过来源路由自动判断过渡效果

利用Vue Router的route.from属性获取上一页的路由信息,动态绑定过渡名称:

<template>
  <Transition :name="transitionName" mode="out-in">
    <!-- 首页内容区域 -->
  </Transition>
</template>

<script setup>
import { computed } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()

// 计算当前应使用的过渡名称
const transitionName = computed(() => {
  const fromPath = route.from?.path || ''
  // 根据来源路径匹配对应过渡
  if (fromPath.includes('/gallery')) {
    return 'slide-left'
  } else if (fromPath.includes('/intro')) {
    return 'dissolve'
  }
  // 默认过渡效果
  return 'slide-left'
})
</script>

<style scoped>
/* slide-left 过渡样式 */
.slide-left-enter-from {
  transform: translateX(100%);
}
.slide-left-enter-active,
.slide-left-leave-active {
  transition: transform 0.5s ease;
}
.slide-left-leave-to {
  transform: translateX(-100%);
}

/* dissolve 过渡样式 */
.dissolve-enter-from,
.dissolve-leave-to {
  opacity: 0;
}
.dissolve-enter-active,
.dissolve-leave-active {
  transition: opacity 0.5s ease;
}
</style>

方案二:跳转时主动传递过渡类型(更可控)

在来源页面跳转首页时,通过查询参数指定过渡效果,首页读取参数后应用对应过渡:

  1. 来源页面(gallery/intro)的跳转逻辑:
// gallery页面跳转首页
router.push({ path: '/', query: { transition: 'slide-left' } })

// intro页面跳转首页
router.push({ path: '/', query: { transition: 'dissolve' } })
  1. 首页组件中读取参数并应用过渡:
<template>
  <Transition :name="transitionName" mode="out-in">
    <!-- 首页内容区域 -->
  </Transition>
</template>

<script setup>
import { computed } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()

const transitionName = computed(() => {
  // 读取查询参数,无参数时用默认值
  return route.query.transition || 'slide-left'
})
</script>

<style scoped>
/* 同方案一的过渡样式 */
.slide-left-enter-from {
  transform: translateX(100%);
}
.slide-left-enter-active,
.slide-left-leave-active {
  transition: transform 0.5s ease;
}
.slide-left-leave-to {
  transform: translateX(-100%);
}

.dissolve-enter-from,
.dissolve-leave-to {
  opacity: 0;
}
.dissolve-enter-active,
.dissolve-leave-active {
  transition: opacity 0.5s ease;
}
</style>

注意事项

  • 若用户直接输入URL访问首页,route.from会为空,此时会触发默认过渡效果;方案二也可通过默认值处理该场景。
  • 过渡样式的时长、动画曲线可根据需求自行调整。

内容的提问来源于stack exchange,提问作者edu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 02:10:18