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

Vue transition组件中<slot/>的Leave过渡效果失效

问题分析与修复方案

1. 过渡类名配置不完整

你的transition组件仅配置了appear(初始渲染过渡)和leave相关类,缺少切换时进入过渡的必要配置,同时类名覆盖场景有误:

  • appear-*类仅作用于组件首次渲染的过渡,切换内容时的进入过渡需要单独配置enter-from-class和enter-active-class。
  • 需补充完整进入、离开、初始渲染三种场景的动画类配置,确保切换流程的过渡逻辑完整。

2. Slot内容缺少唯一标识(key)

Vue过渡系统依赖key属性识别DOM元素变化:当slot内的组件/内容切换时,必须给动态元素添加唯一key,否则Vue会复用DOM节点,直接替换内容而跳过leave过渡流程。


修改后的default-layout.vue代码

<template>
  <div class="bg-slate-900">
    <c-header/>
    <transition
      mode="out-in"
      <!-- 初始渲染过渡配置 -->
      appear-from-class="opacity-0"
      appear-active-class="transition duration-1000"
      <!-- 切换时进入过渡配置 -->
      enter-from-class="opacity-0"
      enter-active-class="transition duration-1000"
      <!-- 离开过渡配置 -->
      leave-to-class="opacity-0"
      leave-active-class="transition duration-1000"
      appear>
      <slot/>
    </transition>
  </div>
</template>

在index.vue中使用时添加key

确保slot内动态切换的内容带有唯一key,可根据路由、组件类型或状态值设置:

<template>
  <default-layout>
    <!-- 示例:根据路由路径作为key -->
    <component :is="currentComponent" :key="$route.path" />
    
    <!-- 条件渲染场景示例 -->
    <!-- <component-a v-if="showComponentA" key="component-a" />
    <component-b v-else key="component-b" /> -->
  </default-layout>
</template>

额外说明

  • mode="out-in"配置正确,可保证旧元素完全离开后新元素才开始进入,无需修改。
  • 确认Tailwind CSS类(opacity-0、transition duration-1000)已正确加载,无样式冲突。

内容的提问来源于stack exchange,提问作者Artur Müller Romanov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:50:18