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?

More than 1 year has passed since last update.

【Vue.js】Vue Routerとは

Posted at

Vue Routerとは

Vue.jsを使用し、SPA構築を行うための公式プラグインです。

Vue Routerを使用してSPAを構築するとあるページから別のページに移動する際にページ全体の情報を読み込む必要がなくなります。

ページ間で共通の箇所は更新が行われません。共通でない箇所のみ書き換えが行われます。不必要な更新が行われないため、ページの移動をよりスムーズに行うことができます。

導入

インストール

npm install vue-router

routes.js

src/router/routes.js
import RecipesPage from '../pages/RecipesPage.vue'
import LoginPage from '../pages/LoginPage.vue'
import RegisterPage from '../pages/RegisterPage.vue'

const routes = [
    {
        path: "/recipes",
        component: RecipesPage,
        name: 'recipe'
    },
    {
        path: "/login",
        component: LoginPage,
        name: 'login'
    },
    {
        path: "/register",
        component: RegisterPage,
        name: 'register'
    },
]

export default routes

nameにより、名前からルートを特定します。(名前付きルート)

index.js

src/router/index.js
import { createRouter, createWebHashHistory } from "vue-router";
import routes from "./routes";

export default createRouter({
    routes,
    history: createWebHashHistory()
})

createRouter()により、ルーティング情報を扱うルータの生成が可能になります。

Historyは後ほど説明します。

main.js
import route from './router';

const app = createApp(App);
app.use(route)
app.mount('#app');
App.vue
<script setup>
import Navbar from './components/Navbar.vue';
import Footer from './components/Footer.vue'

</script>

<template>
  <Navbar />
  <router-view />
  <Footer />
</template>


ハッシュとヒストリーの違い

Vue Routerのルーティング設定ではアクセスするURLのモードをハッシュモード、ヒストリーモードから選択することができます。

ハッシュモード

アクセスするURLにハッシュ文字(#)を含めてルーティングします。これによりサーバーへの接続なしで運用ができるため、ヒストリーモードより処理が高速です。

〇デメリット
URLの見た目が悪い。

ヒストリーモード

通常のURLでルーティングを行います。サーバーへの接続は必須となるため、通信速度はハッシュモードに比べて劣ります。

〇デメリット
HTML5 History APIをサポートしていないブラウザでは使用できない。

HIstory APIとは

Webページの履歴情報を操作できるJavaScriptの機能です。普段からよく使うブラウザ機能の「戻る」や「進む」に加え、「追加」や「変更」なども操作ができます。

// 前のページに戻る
window.history.back();
// 次のページへ進む
window.history.forward();

router-link

routes.jsで定義した名前を使うことで簡単にページ遷移が実現します。

Navbar.vue
<a 
  href="#"
  @click.prevent="$event => $router.push('/recipes')" 
  class="mr-5 hover:text-gray-900"
>
  Recipes
</a>
<router-link 
  :to="{ name: 'summary' }"
  class="mr-5 hover:text-gray-900"
  >
  Summary
</router-link>

名前付きルートにリンクすためには。router-linkコンポーネントのtoプロパティにオブジェクトを渡します。

ルートコンポーネントにプリパティを渡す

コンポーネントで$routeを追加うとコンポーネントとルートの間に密結合が生まれ、コンポーネントが特定のURLでしか使用できないなどの制限できます。

これを使って404エラー画面を作成しました。

参考文献

ルートメタフィールド

ルートに任意の情報を添付したい場合、プロパティのオブジェクトを受け入れ、ルートの場所とナビゲーションガードでアクセスできるmetaプロパティを介して実現できます。

これを使って、ログインしていないユーザーにはログイン画面を表示する処理を追加しました。↓

src/router/routes.js
    {
        path: "/recipes",
        component: RecipesPage,
        name: 'recipes',
        // 追加
        meta: {
            auth: true
        }
    },
    {
        path: "/summary",
        component: SummaryPage,
        name: 'summary',
        // 追加
        meta: {
            auth: true
        }
    },
src/router/index.js
const router = createRouter({
    routes,
    history: createWebHistory(),
    // linkActiveClass: 'active'
});

router.beforeEach((to, from) => {
    if (to.meta.auth) {
        return { 
            name: "login",
            query: {
                redirect: to.fullPath
            },
        };
    }
});

export default 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?