1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Vue.js] Vue Router を使用して画面遷移前もしくは画面遷移後に処理を行う方法

Posted at

logo-green-black.png

はじめに

Vue.js は、シンプルかつ強力な JavaScript フレームワークであり、シングルページアプリケーション(SPA)の開発に広く使われています。 Vue Router は、 アプリケーションにルーティング機能を追加するための公式ライブラリです。この記事では、 Vue Router を使用して、画面遷移前や遷移後に特定の処理を実行する方法について解説します。

Vue Router の基本

Vue Router を使用すると、アプリケーション内の異なるページやコンポーネント間を簡単に遷移することができます。ルートを設定し、各ルートに対応するコンポーネントを指定することで、画面遷移が可能になります。

Vue Router のインストール

まず、Vue Router をインストールします。Vue CLI を使用してプロジェクトを作成している場合、 vue-router は自動的にインストールされますが、手動でインストールする場合は以下のコマンドを使用します。

npm install vue-router

次に、 router.js ファイルを作成してルートを定義します。

import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/Home.vue';
import About from './components/About.vue';

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

このように定義されたルーターを、 Vue アプリケーションに登録します。

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

const app = createApp(App);
app.use(router);
app.mount('#app');

画面遷移前の処理(ナビゲーションガード)

Vue Router には「ナビゲーションガード」と呼ばれる仕組みがあり、これを使って画面遷移前に特定の処理を行うことができます。ナビゲーションガードは、グローバル、ルートごと、コンポーネントごとに設定できます。

グローバルナビゲーションガード

グローバルナビゲーションガードは、全てのルートに対して適用されるガードです。例えば、ユーザーがログインしていない場合に特定のページへのアクセスを防ぐといった処理に使用できます。

router.beforeEach((to, from, next) => {
  // 認証が必要なページの判定
  if (to.path === '/about' && !isAuthenticated()) {
    // 未認証の場合はログインページにリダイレクト
    next('/');
  } else {
    // 続行
    next();
  }
});

function isAuthenticated() {
  // 実際の認証ロジックをここに記述
  return false; // 認証されていないと仮定
}

ルートごとのナビゲーションガード

特定のルートに対してナビゲーションガードを設定することもできます。これは、ルート定義に直接 beforeEnter を設定することで実現できます。

const routes = [
  { path: '/', component: Home },
  {
    path: '/about',
    component: About,
    beforeEnter: (to, from, next) => {
      if (isAuthenticated()) {
        next();
      } else {
        next('/');
      }
    }
  }
];

コンポーネントごとのナビゲーションガード

コンポーネント内で画面遷移前の処理を行いたい場合は、 beforeRouteEnter や beforeRouteLeave メソッドを使用します。

export default {
  name: 'About',
  beforeRouteEnter(to, from, next) {
    // コンポーネントが描画される前に呼ばれる
    console.log('Entering About component');
    next();
  },
  beforeRouteLeave(to, from, next) {
    // コンポーネントが離れる前に呼ばれる
    console.log('Leaving About component');
    next();
  }
};

画面遷移後の処理

画面遷移が完了した後に特定の処理を行いたい場合は、 afterEach フックを使用します。例えば、ページ遷移後に Google Analytics でページビューを記録するなどの処理が考えられます。

router.afterEach((to, from) => {
  console.log('Successfully navigated to:', to.path);
  // ここにページ遷移後の処理を記述
});

まとめ

Vue Router を使用することで、アプリケーションにおける柔軟な画面遷移制御が可能になります。ナビゲーションガードを活用して、画面遷移前後に特定の処理を実行することで、ユーザーエクスペリエンスを向上させたり、セキュリティを強化したりすることができます。今回紹介したテクニックを活用して、より効率的なアプリケーションを構築してください。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?