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

Vue2中transition-group结合v-show二次切换过渡失效问题

Vue2 TransitionGroup 二次切换过渡延迟失效问题解决

问题说明

在Vue2的<transition-group>内为元素添加transition-delay过渡效果时,首次显示/隐藏过渡正常,但二次切换时过渡效果失效。已排查key、过渡样式、元素样式等问题,不想使用v-if(会移除DOM元素),也不想用setTimeout,需要可行解决方案。

问题根源

直接通过内联样式给元素绑定transition和transition-delay时,<transition-group>在处理二次切换(元素从display:none恢复/隐藏)时,无法正确触发带有延迟的过渡逻辑——因为元素始终存在于DOM中,Vue的过渡钩子无法重新识别内联的过渡配置。

解决方案

将过渡配置(包括延迟)移到CSS的过渡激活类中,通过自定义属性或类来为不同元素设置差异化延迟,避免内联样式的冲突。同时确保<transition-group>的过渡类正确应用。

修正后的代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>v-show标签过渡实现特效单项目探究</title>
    <script src="vue.js"></script>
    <style>
        .divwidth {
            width: 60%;
            margin-top: 15px;
        }

        .content {
            background-color: orange;
            width: auto;
            padding: 6px;
            font-size: 20px;
            border-radius: 8px;
        }

        /* 基础过渡激活类,统一过渡属性 */
        .hello-enter-active, .hello-leave-active {
            transition: all var(--transition-duration) ease;
            transition-delay: var(--transition-delay);
        }

        .hello-enter, .hello-leave-to {
            opacity: 0;
            transform: translateX(50%);
        }

        /* 为不同元素设置自定义过渡参数 */
        .item-1 {
            --transition-duration: 500ms;
            --transition-delay: 100ms;
        }

        .item-2 {
            --transition-duration: 300ms;
            --transition-delay: 100ms;
        }
    </style>
</head>
<body>
<div id="root">
    <button @click="isShow2=!isShow2">显示/隐藏(单个transition)</button>
    <transition name="hello" appear>
        <div class="divwidth item-1" v-show="isShow2">
            <span class="content">英语第1次考试</span>
        </div>
    </transition>

    <button @click="isShow=!isShow">显示/隐藏(transition-group)</button>
    <transition-group name="hello" appear>
        <div class="divwidth item-1" v-show="isShow" key="11">
            <span class="content">英语第1次考试</span>
        </div>
        <div class="divwidth item-2" v-show="isShow" key="12">
            <span class="content">英语第2次考试</span>
        </div>
    </transition-group>
</div>
</body>
<script>
    new Vue({
        el: "#root",
        data() {
            return {
                isShow: true,
                isShow2: true
            }
        },
    })
</script>
</html>

关键调整点

  • 移除元素上的内联transition和transition-delay样式,改用CSS自定义属性(--transition-duration、--transition-delay)来管理过渡参数
  • 在.hello-enter-active和.hello-leave-active中引用自定义属性,确保过渡逻辑由Vue的过渡类统一控制
  • 通过不同的元素类(item-1、item-2)为每个元素设置差异化的过渡时长和延迟

这样调整后,<transition-group>在每次切换时都会正确应用过渡类,触发带有延迟的过渡效果,二次切换也能正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 05:30:53