vue 输入转换无法正常工作

Car*_*llo 4 javascript css animation vue.js vuejs2

我正在开发一个项目,其中我必须使用进入和离开动画来渲染一些组件,当组件进入屏幕时,它必须从底部进入,当它离开时,它必须向上执行,这是所需的行为是,当我更改组件标记的 :is 属性时,当前组件向上移动,下一个组件从底部移动,代码如下所示:

<template>
  <div class="home">
    <transition name="section">
      <component :is="activeSection"></component>
    </transition>
  </div>
</template>

<script>
import comp1 from './comp1';
import comp2 from './comp2';

export default {
  components: {
    comp1,
    comp2
  },
  data() {
    activeSection: 'comp1'
  }
</script>

<style scoped>
  .section-enter {
    top: 100vh;
  }
  .section-enter-to {
    top: 0vh;
  }
  .section-enter-active {
    animation-name: 'slideIn';
    animation-duration: 1s;
  }
  .section-leave {
    top: 0vh;
  }
  .section-leave-active {
    animation-name: 'slideOut';
    animation-duration: 1s;
  }
  .section-leave-to {
    top: -100vh;
  }


  @keyframes slideIn {
    from {
      top: 100vh;
    }
    to {
      top: 0
    }
  }

  @keyframes slideOut {
    from {
      top: 0vh;
    }
    to {
      top: -100vh;
    }
  }
</style>
Run Code Online (Sandbox Code Playgroud)

但实际行为是第一个组件向上移动,但第二个组件在没有动画的情况下立即出现。

如果我一次渲染一个(不是破坏一个并使用相同的操作渲染另一个),一切都会完美运行。我不知道发生了什么事。

ton*_*y19 5

您的 CSS 存在一些问题。

CSS 过渡和 CSS 动画

可以使用CSS 过渡 CSS 动画实现过渡。在这种情况下,您的 CSS 错误地混合了这两个概念。

特别是,slideIn关键帧和.section-enter/规则有效地执行移入视图.section-enter-to的相同任务。.section但是,这缺少transition动画更改所需的非零时间规则,因此更改会立即发生。slideOut关键帧和规则也存在同样的问题leave

.section-enter {
  top: 100vh;
}
.section-enter-to {
  top: 0;
}
.section-enter-active {
  transition: .5s; /* MISSING RULE */
}

.section-leave {
  top: 0;
}
.section-leave-to {
  top: -100vh;
}
.section-leave-active {
  transition: .5s; /* MISSING RULE */
}
Run Code Online (Sandbox Code Playgroud)

删除关键帧并添加缺少的规则(如上所示)将产生有效的 CSS 过渡。

演示1

使用 CSS 动画

或者,您可以将关键帧与 CSS 动画结合使用,其中动画仅按规则应用*-active,并且不使用*-enter/规则。请注意,您的问题在 中包含不必要的引号,这是无效的语法,将被静默忽略(不会发生动画)。我在下面的代码片段 ( ) 中使用了更简单的简写*-leaveanimation-name: 'slideIn';animation: slideIn 1s;

.section-enter-active {
  animation: slideIn 1s;
}
.section-leave-active {
  animation: slideOut 1s;
}

@keyframes slideIn {
  from {
    top: 100vh;
  }
  to {
    top: 0;
  }
}
@keyframes slideOut {
  from {
    top: 0;
  }
  to {
    top: -100vh;
  }
}
Run Code Online (Sandbox Code Playgroud)

演示2

优化 CSS 过渡

您还可以使用而不是过渡来调整动画性能translateYtop

/* top initially 0 in .wrapper */

.section-leave-active,
.section-enter-active {
  transition: .5s;
}
.section-enter {
  transform: translateY(100%);
}
.section-leave-to {
  transform: translateY(-100%);
}
Run Code Online (Sandbox Code Playgroud)

演示3