Vue.js 中的动画有哪些类型?如何使用它们?

Vue.js 中的动画分为两大类型:

  1. 过渡动画(Transitions):
  • 是两个状态切换时的动画。
  • 它会为某个元素自动应用样式,在过渡过程中平滑地改变这些样式。
  • 需要配合 或 组件使用。

使用方式:

html
<transition>
  <div v-if="show">Hello</div> 
</transition>
  1. 动画(Animations):
  • 是通过关键帧来定义动画序列。
  • 需要通过 @keyframes 规则生成关键帧,然后应用动画样式。
  • 可以配合 或 标签使用。

使用方式:

html
<div :style="{ animation: 'bounce .5s' }">...</div> 

css
@keyframes bounce {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-20px);
  }
  100% {
    transform: translateY(0);
  }
}

示例:
过渡动画:

html 
<transition name="bounce">
  <div v-if="show">Hello</div>
</transition> 
css
.bounce-enter-active {
  animation: bounce-in .5s;
}

.bounce-leave-active {
  animation: bounce-out .5s; 
}

@keyframes bounce-in {
  0% {
    transform: scale(0);
  }
  50% {
    transform: scale(1.5);
  }
  100% {
    transform: scale(1);
  }  
}

@keyframes bounce-out {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.5);
  }
  100% {
    transform: scale(0);
  }  
} 

动画:

html
<div :style="{ animation: 'bounce .5s' }">...</div>  
css
@keyframes bounce {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-20px);
  }
  100% {
    transform: translateY(0);
  }
}