【问题标题】:Vue transition works for "enter" state but not for "leave" stateVue 转换适用于“进入”状态,但不适用于“离开”状态
【发布时间】:2021-08-10 20:07:21
【问题描述】:

我在半透明背景上呈现了一个模态。两个元素都有一个v-if,由同一个变量控制。

虽然enter 过渡动画效果很好,但`leave` 过渡动画被忽略(它应该平滑地淡出,而不是立即消失)。为什么?

Codepen

标记:

<div id="app">
  <button @click="showModal = !showModal">Toggle Modal</button>
  
  <div v-if="showModal" class="modalBackdrop">
    <transition name="content" appear>
      <div v-if="showModal" class="modalContent">
        Modal
      </div>
    </transition>
  </div>
</div>

CSS:

.content-enter-active {
  animation: slide-up .75s;
}

.content-leave-active {
  animation: fade-out .75s;
}

@keyframes slide-up {
  0% {
    transform: translateY(100%);
  }
  100% {
    transform: translateY(0);
  }
}

@keyframes fade-out {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

【问题讨论】:

    标签: vue.js vue-transitions


    【解决方案1】:

    showModal 为假时,过渡元素立即被销毁。如果您在转换父级中使用v-if="showModal" 的唯一原因是禁用modalBackdrop,那么您可以动态分配此类。

    这是按预期工作的:

      <div :class="{ modalBackdrop: showModal }">
        <transition name="content" appear>
          <div v-if="showModal" class="modalContent">
            Modal
          </div>
        </transition>
      </div>
    

    【讨论】:

      【解决方案2】:

      似乎 modalBackdrop 类的 div 在 modalContent 类的嵌套 div 进行转换之前消失了,所以尝试用名称为 backdrop 的转换组件包装模态背景,该组件也采用 fade-out动画:

      .backdrop-leave-active,.content-leave-active { /*.backdrop-leave-active is sufficient since the parent opacity is applied on children*/
        animation: fade-out .75s;
      }
      

      模板:

      <div id="app">
        <button @click="showModal = !showModal">Toggle Modal</button>
        <transition name="backdrop" appear>
          <div v-if="showModal" class="modalBackdrop">
            <transition name="content" appear>
              <div v-if="showModal" class="modalContent">
                Modal
              </div>
            </transition>
          </div>
        </transition>
      </div>
      

      DEMO

      【讨论】:

        猜你喜欢
        • 2021-07-19
        • 2020-08-16
        • 1970-01-01
        • 2015-01-02
        • 1970-01-01
        • 2015-03-03
        • 2018-04-30
        • 2014-06-19
        • 1970-01-01
        相关资源
        最近更新 更多