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

如何用Vue Transition实现模态框子元素的退出缩小动画?

如何为Vue Transition组件的子元素添加退出动画

我有一个模态框组件,通过.modal-open-class在挂载时实现了模态框的放大动画,但关闭时该动画无法生效,想知道能否利用<Transition>组件为子元素添加退出时的缩小动画。

原组件代码

<Transition name="fade-modal">
  <div v-if="open" class="overlay-classes-here" style="z-index: 99999">
    <div id="modalIndicator" :class="{...'modal-open-class': open }" class="modal-classes-here">
      <slot name="modalContent"></slot>
    </div>
  </div>
</Transition>

原CSS样式

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

.fade-modal-enter-from,
.fade-modal-leave-to  {
    opacity: 0;
}

.modal-open-class {
  animation: blowUpModal .5s cubic-bezier(0.165, 0.840, 0.440, 1.000) forwards;
}

@keyframes blowUpModal {
  0% {
    transform: scale(0);
  }
  100% {
    transform: scale(1);
  }
}

问题原因

退出时open变为false,.modal-open-class会被立即移除,且<Transition>的状态类仅作用于根元素,子元素没有触发退出动画的条件,导致缩小效果无法执行。

纯CSS解决方案(推荐)

利用<Transition>自动添加的状态类,通过根元素的过渡状态来控制子元素的动画,同步遮罩层和模态框的过渡周期:

  1. 修改CSS样式:
/* 遮罩层的透明度过渡保留 */
.fade-modal-enter-active,
.fade-modal-leave-active {
  transition: opacity 0.5s ease;
}

.fade-modal-enter-from,
.fade-modal-leave-to {
  opacity: 0;
}

/* 进入时:通过根元素的enter-active状态触发子元素放大动画 */
.fade-modal-enter-active .modal-classes-here {
  animation: blowUpModal 0.5s cubic-bezier(0.165, 0.840, 0.440, 1.000) forwards;
}

/* 退出时:通过根元素的leave-active状态触发子元素缩小动画 */
.fade-modal-leave-active .modal-classes-here {
  animation: shrinkModal 0.5s cubic-bezier(0.165, 0.840, 0.440, 1.000) forwards;
}

@keyframes blowUpModal {
  0% { transform: scale(0); }
  100% { transform: scale(1); }
}

@keyframes shrinkModal {
  0% { transform: scale(1); }
  100% { transform: scale(0); }
}
  1. 简化组件代码(移除原有的动态类绑定):
<Transition name="fade-modal">
  <div v-if="open" class="overlay-classes-here" style="z-index: 99999">
    <div id="modalIndicator" class="modal-classes-here">
      <slot name="modalContent"></slot>
    </div>
  </div>
</Transition>

原理说明

<Transition>组件在进入/退出阶段会为包裹的根元素自动添加以下状态类:

  • 进入阶段:fade-modal-enter-from → fade-modal-enter-active → fade-modal-enter-to
  • 退出阶段:fade-modal-leave-from → fade-modal-leave-active → fade-modal-leave-to

通过根元素的fade-modal-enter-active和fade-modal-leave-active状态,我们可以精准控制子元素的动画触发时机,确保进入/退出动画与遮罩层的透明度过渡同步完成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:03:33