現代の 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>
-
Vue Router を使うことで、複数の「画面」を持つ SPA を効率的に構築できます。
Top comments (3)
pretty cool seeing this all laid out so simple - always makes me wonder if building a perfect router setup comes from trial and error or just reading docs over and over
Thanks !!! You are a diligent thinker. I don't know the answer and make effort to handle the balance between writing trial code which often causes errors and reading docs, with joy of learning 😁
Some comments may only be visible to logged-in visitors. Sign in to view all comments.