LoginSignup
41
39

More than 5 years have passed since last update.

Vue.jsとanimete.cssでアニメーション

Posted at

Vue.js

vueでSPA作るならvue-routerもほぼ必須。

$ npm install vue vue-router --save

コンポーネントを作る

今回はscriptタグでテンプレートを記述するがvue-loaderなどを使うと1ファイル1コンポーネントで分離して書けるので便利。

    script(id='page-1' type='x-template')
      .page
        h1 ページ1
        img(src='img/page-1.gif' alt='page-1')

js側でhtmlに書いたテンプレートを拾ってコンポーネントを登録する。
vue-routerを使ってroute別に表示/非表示を切り替える。

components.p1 = Vue.component('page-1', {
  template: '#page-1'
});

animate.css

https://github.com/daneden/animate.css
全部は入らないのでいるアニメーションだけとってくる。
今回は表示にfadeInUp、非表示にslideOutRightを使う。

デフォルトのままだと表示と非表示のアニメーションが同時に発火するため、新しく入ってくるコンポーネントが前のコンポーネントに引っかかってカクつく。

https://gyazo.com/d4f9bbdaeb3925397da0152575c48c93

そこで表示のアニメーションに animation-delay を指定して前のコンポーネントが消えるまで表示アニメーションを遅延させる。

/* アニメーション */
// 表示: fadeInUp
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translate3d(0, 100%, 0);
  }

  to {
    opacity: 1;
    transform: none;
  }
}

.fadeInUp {
  animation-name: fadeInUp;
  animation-delay: 0.5s; // 前のコンポーネントが消えるまで遅延させる
  animation-duration: 1s;
  animation-fill-mode: both;
}

// 非表示: slideOutRight
@keyframes slideOutRight {
  from {
    transform: translate3d(0, 0, 0);
  }

  to {
    visibility: hidden;
    transform: translate3d(100%, 0, 0);
  }
}

.slideOutRight {
  animation-name: slideOutRight;
  animation-duration: 0.5s; // fadeInUpのanimation-delayと一致させる
  animation-fill-mode: both;
}

トランジションを登録する

Vue.transition('page', {
  enterClass: 'fadeInUp',
  leaveClass: 'slideOutRight',
});

要素にトランジションを適用する

    script(id='page-1' type='x-template')
      .page(transition='page') //- 登録したpageトランジションを適用
        h1 ページ1
        img(src='img/page-1.gif' alt='page-1')

動作

最終的な動作がこちら。カクつきがなくなった。

https://gyazo.com/c7331678041345ec7db3ea2c45bf3c40

おまけ

作ったサンプルページとソース置き場。

41
39
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
41
39