Vue.jsでAnimate.cssを活用したアニメーション実装

Animate.cssは、CSSベースのアニメーション効果を簡単に実装できる人気のライブラリです。Velocity.jsなどのJavaScriptアニメーションライブラリとは異なり、CSSクラスの付与だけで動作します。

インストールと準備

パッケージマネージャーでインストールします。

npm install animate.css

Vueコンポーネントで読み込みます。

import 'animate.css'

基本的な使用方法

テンプレート側でアニメーション対象の要素を用意します。

<template>
  <div class="container">
    <button @click="triggerAnimation">アニメーション実行</button>
    <div ref="targetEl" class="box">対象要素</div>
  </div>
</template>

メソッド内でクラスを動的に追加します。アニメーション終了後にクラスを削除することで、繰り返し実行可能にします。

<script>
export default {
  methods: {
    triggerAnimation() {
      const element = this.$refs.targetEl
      const animationClass = 'animate__animated animate__bounceOutLeft'
      
      element.classList.add(...animationClass.split(' '))
      
      element.addEventListener('animationend', () => {
        element.classList.remove(...animationClass.split(' '))
      }, { once: true })
    }
  }
}
</script>

主要なアニメーション効果

フェード系

クラス名効果
animate__fadeInフェードイン
animate__fadeInDown上からフェードイン
animate__fadeInUp下からフェードイン
animate__fadeOutフェードアウト
animate__fadeOutLeft左へフェードアウト

バウンス系

クラス名効果
animate__bounceInバウンスで出現
animate__bounceOutバウンスで消失
animate__bounceInUp下からバウンスイン

ズーム系

クラス名効果
animate__zoomInズームイン
animate__zoomOutズームアウト
animate__zoomInRight右からズームイン

回転系

クラス名効果
animate__rotateIn回転しながら出現
animate__rotateOutDownLeft左下へ回転消失
animate__rotateInUpRight右上から回転イン

フリップ系

クラス名効果
animate__flipInXX軸フリップイン
animate__flipOutYY軸フリップアウト

アクセント系(繰り返し)

クラス名効果
animate__bounce跳ねる
animate__pulse脉動
animate__shakeX左右に揺れる
animate__tada拡縮しながら揺れる
animate__swing振り子のように揺れる

応用:コンポーネント化

再利用可能なアニメーションラッパーコンポーネントを作成します。

<template>
  <transition
    enter-active-class="animate__animated animate__fadeInUp"
    leave-active-class="animate__animated animate__fadeOutDown"
  >
    <slot v-if="visible" />
  </transition>
</template>

<script>
export default {
  props: {
    visible: Boolean
  }
}
</script>

CSS変数でアニメーション速度を調整することも可能です。

:root {
  --animate-duration: 0.5s;
  --animate-delay: 0.2s;
}

タグ: vue.js Animate.css CSSアニメーション フロントエンド UI/UX

9月6日 20:02 投稿