現代の Web アプリの多くは SPA (エスピーエー、Single Page Application) と呼ばれる形式で作られています。これは、ページ遷移してもブラウザの再読み込みがなく、スムーズなユーザー体験を提供するアプリのことです。
異なる「ページ」への URL の切替え
SPA において、異なる「ページ」への URL の切替えや、それに応じたコンポーネントの表示を管理するのが ルーティング (routing) ライブラリ です。
ルーティング (routing)
Vue では公式のルーティングライブラリとして Vue Router (vue-router
) が広く使われています。
URL 切替えと Vue ルーティング
+-------------------------------------------------------+
| Web / アプリ サーバー |
+-------------------------------------------------------+
^
| Vue Router 管轄外の場合、
| サーバーリクエスト
|
+-------------------------------------------------------+
| ブラウザ (SPA) |
+-------------------------------------------------------+
| URL: example.com/ URL: example.com/about |
| |
| +--------------------+ +--------------------+ |
| | HomeView | | AboutView | |
| | コンポーネント | | コンポーネント | |
| +--------------------+ +--------------------+ |
| ^ ^ |
| | (コンポーネント表示) | |
| +---------------+---------------+ |
| | <router-view> | |
| +---------------+---------------+ |
| ^ |
| | |
| (ルーティングの決定) |
| +---------------+---------------+ |
| | Vue Router | |
| +-------------------------------+ |
| ^ |
| | |
| (URL 切替え リクエスト) |
+-------------------------------------------------------+
Vue Router を使ってみよう
- インストール: プロジェクトに Vue Router をインストールします。
npm install vue-router
- ルーターの定義:
router/index.js
のようなファイルで、どのURLでどのコンポーネントを表示するかを定義します。// router/index.js import { createRouter, create Web History } from 'vue-router' import HomeView from '../views/HomeView.vue' import AboutView from '../views/AboutView.vue' const routes = [ { // ルートパス (トップページ) path: '/', name: 'home', component: HomeView }, { // /about パス path: '/about', name: 'about', component: AboutView } ] const router = createRouter({ // HTML 5 History モードを使用 history: create Web History(), routes }) export default router
- Vue アプリへの組み込み:
main.js
などのエントリーポイントで、Vue アプリにルーターを組み込みます。// main.js import { createApp } from 'vue' import App from './App.vue' // ルーターをインポート import router from './router' const app = createApp(App) // ルーターをアプリに適用 app.use(router) app.mount('#app')
- コンポーネントでの使用
<router-link>
- クリックするとページ遷移するリンクを作成します。HTML の
<a>
タグに似ていますが、SPA の内部遷移を担います。<template> <nav> <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> </nav> </template>
<router-view>
- 現在の URL に対応するコンポーネントが描画される場所です。
<template> <router-view></router-view> </template>
- クリックするとページ遷移するリンクを作成します。HTML の
Vue Router を使うことで、複数の「画面」を持つ SPA を効率的に構築できます。