LoginSignup
10
13

More than 3 years have passed since last update.

Vue.jsのSPAで、進む/戻るのアクションに応じてページ遷移のアニメーションを切り替える

Last updated at Posted at 2019-06-18

概要

Vue.js+Vue RouterのSPAで、<transition>を使うことによって、アニメーションを伴ってページ遷移を実現することができる。本記事では、ページが戻るときのアニメーションと進むときのアニメーションを切り替える方法をまとめます。
ソースコードはポイントになる部分しか書いていないので、そのままでは動かないかもしれません。

全体の流れ

  1. <router-view>要素を<transition>で囲む
  2. watchプロパティに$routeを追加する
  3. to, fromのページ番号を比較し、大小関係に応じてアニメーションを切り替える

ソースコード

router

ルーターはこんな感じで設定します。
ポイントは、メタ情報としてページ番号を定義するところです(キー名はなんでも良いですが、ここではmeta.indexとしています)。この番号を比較することで「進む」アクションなのか「戻る」アクションなのかを判定します。

index.js
import Vue from 'vue';
import Router from 'vue-router';
import First from '@/components/First';
import Second from '@/components/Second';
Vue.use(Router);

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'first',
      component:First,
      meta: {
        index: 0, // ページ番号
      },
    },
    {
      path: '/second',
      name: 'second',
      component: Second,
      meta: {
        index: 1,
      },
    },
  ],
});

ベースコンポーネント

アプリケーションのベースとなるコンポーネントを編集します。
vue-cliでプロジェクトを初期化した場合はApp.vueという名前で作成されます。<router-view>がルーティングで設定した各ページのコンポーネントが表示される部分になります。
ポイントはwatchプロパティ内で$routeを監視しているところになります。ここで、$routeの遷移前、遷移後のルーティングオブジェクトを取得し、先程設定したメタ情報のページ番号を前後で比較することによって、進む・戻るのアクションに応じてアニメーションを切り替えることができます。

App.vue
<template>
  <div id="app">
    <v-app>
      <div class="app-header">
        <!-- ヘッダー画像 -->
      </div>

        <div class="app-content">
          <transition
            name="costom-transition"
            :duration="transition.duration"
            :enter-active-class="transition.enter"
            :leave-active-class="transition.leave"
            >            
              <router-view></router-view>
          </transition>
        </div>
      </v-app>
  </div>
</template>

<script>
export default {
  name: 'app',
  watch: {
    $route(to, from) {
      // アニメーションの切り替え
      if (to.meta.index > from.meta.index) {
        this.transition.enter = '進むときのenterアニメーション';
        this.transition.leave = '進むときのleaveアニメーション';
      } else {
        this.transition.enter = '戻るときのenterアニメーション';
        this.transition.leave = '戻るときのleaveアニメーション';
      }
    },
  },
  data() {
    return {
      transition: {
        enter: '',
        leave: '',
        duration: 100,
      },
    };
  },
};
</script>

アニメーション

アニメーションの実装はAnimate.cssが手軽で便利です。

10
13
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
10
13