Vue 3 アプリケーションでページ遷移を実現するには、公式ルーティングライブラリである vue-router@4 を導入・構成します。本稿では、最小限の動作を担保する基本設定から、動的ルーティング、ナビゲーション制御までを実践的に解説します。
1. ライブラリのインストール
プロジェクトに vue-router を追加します:
npm install vue-router@4
yarn add vue-router@42. ルーターの初期化とルート定義
ルート設定ファイル(例:src/router/index.js)を作成し、以下のように構成します:
import { createRouter, createWebHistory } from 'vue-router';
import Dashboard from '@/views/Dashboard.vue';
import Profile from '@/views/Profile.vue';
import NotFound from '@/views/NotFound.vue';
const routeConfig = [
{
path: '/',
name: 'Dashboard',
component: Dashboard,
meta: { title: 'ダッシュボード' }
},
{
path: '/profile/:id',
name: 'UserProfile',
component: Profile,
props: true,
meta: { requiresAuth: true }
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: NotFound
}
];
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: routeConfig
});
// ナビゲーションガード(例:認証チェック)
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated()) {
next('/login');
} else {
document.title = to.meta.title || 'Vue App';
next();
}
});
export default router;上記では、createWebHistory を用いて HTML5 History API モードを有効化しています。これにより、# を含まないクリーンな URL(例:/profile/123)が利用可能になります。代替としてハッシュモードを利用する場合は createWebHashHistory() を指定します。
3. ルートコンポーネントの表示
アプリケーションのルートテンプレート(例:App.vue)に <router-view> を配置します:
<template>
<header>
<nav>
<router-link to="/" active-class="active">ホーム</router-link>
<router-link to="/profile/42" active-class="active">プロフィール</router-link>
</nav>
</header>
<main>
<router-view />
</main>
</template>active-class 属性により、現在のルートに対応するリンクに自動でクラスが付与されます。また、<router-view> は名前付きビューをサポートしており、複数の並列表示領域を定義できます:
<router-view />
<router-view name="sidebar" />対応するルート定義では components オブジェクトでマッピングします:
{
path: '/',
components: {
default: Dashboard,
sidebar: UserSidebar
}
}4. Vue アプリへの統合
エントリーポイント(例:main.js)でルーターをアプリケーションに登録します:
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(createPinia());
app.use(router);
app.mount('#app');5. プログラミングによるナビゲーション
Composition API を用いたルート遷移の実装例です:
<template>
<button @click="navigateToProfile">プロフィールへ移動</button>
<button @click="goBack">戻る</button>
<button @click="goForward">進む</button>
</template>
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
const navigateToProfile = () => {
router.push({ name: 'UserProfile', params: { id: '789' } });
};
const goBack = () => router.back();
const goForward = () => router.forward();
// 2ページ戻る
const goTwoStepsBack = () => router.go(-2);
</script>push() は履歴スタックに新規エントリを追加し、replace() は現在のエントリを置き換えます。後者の場合、ブラウザの「戻る」ボタンで元のページに戻れません。例えばログイン後のリダイレクトなど、意図的に履歴を削除したい場面で使用します。
6. 動的インポートによるコード分割
大規模アプリでは、ルートコンポーネントを遅延読み込み(lazy loading)することでバンドルサイズを最適化できます:
{
path: '/admin',
name: 'AdminPanel',
component: () => import('@/views/AdminPanel.vue')
}この記法により、該当ルートに初めてアクセスした際にのみコンポーネントがロードされます。