トッカンソフトウェア

Vue.js ルーティング

今回は、ルーティングをやります。

Vue.jsだけで動作するシンプルなものとVue Routerを使ったものの2パターンをやります。
Vue.jsだけで動作するシンプルなものは本家ページのサンプルがわかりやすかったので
ソースはそのまま持ってきて説明コメントだけ追加します

Vue.jsだけで動作するシンプルなもの

Home.vue

<template>
  <h1>Home</h1>
</template>

About.vue

<template>
  <h1>About</h1>
</template>

NotFound.vue

<template>
  <h1>404</h1>
</template>

App.vue

<script setup>
import { ref, computed } from 'vue'
import Home from './Home.vue'
import About from './About.vue'
import NotFound from './NotFound.vue'

const routes = {
  '/': Home,
  '/about': About
}

const currentPath = ref(window.location.hash)

// hashchangeイベント URLの#より後ろの文字列が変更されたら呼び出し
window.addEventListener('hashchange', () => {

  // hashはURLの#とその後ろの文字列
  // (http://localhost:5173/#/aboutであれば#/aboutを取得)
  currentPath.value = window.location.hash
})

// currentPathが変更されたら再実行
const currentView = computed(() => {

  // slice(1)でcurrentPath.valueの2文字目から最後までの文字列を取得
  // (#/aboutであれば/aboutを取得)
  return routes[currentPath.value.slice(1) || '/'] || NotFound
})
</script>

<template>
  <a href="#/">Home</a> |
  <a href="#/about">About</a> |
  <a href="#/non-existent-path">Broken Link</a>
  <component :is="currentView" />
</template>

component :is=でコンポーネントの切換を行います。
実行イメージ

Vue Router



プロジェクト生成時に指定するオプションでRouterを指定すると、Vue Router関連機能がプロジェクトに追加されます。

npm create vue@latest


*  Select features to include in your project: (↑/↓ to navigate, space to select, a to toggle all, enter to confirm)
|  [•] TypeScript
|  [ ] JSX Support
|  [+] Router (SPA development)
|  [ ] Pinia (state management)
|  [ ] Vitest (unit testing)
|  [ ] End-to-End Testing
|  [ ] ESLint (error prevention)
|  [ ] Prettier (code formatting)
—
src\router\index.js
このファイルは以下の内容で自動生成されます。ここでルーティングの設定を行います。

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
  ],
})

export default router

src\main.js
上記のsrc\router\index.jsファイルを取り込む設定も自動で作成されます。

import './assets/main.css'

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

const app = createApp(App)

app.use(router)

app.mount('#app')

src\App.vue
このファイルも自動生成されるのですが、よりシンプルになるように修正しました。

<script setup>
import { RouterLink, RouterView } from 'vue-router'
</script>

<template>
  <nav>
    <RouterLink :to="{name : 'home'}">Home</RouterLink>
    <RouterLink to="/about">About</RouterLink>
  </nav>
  <RouterView />
</template>

src\views\HomeView.vue
このファイルも自動生成されるのですが、よりシンプルになるように修正しました。

<template>
  <h1>Hello World!!</h1>
</template>

src\views\AboutView.vue
このファイルも自動生成されるのですが、よりシンプルになるように修正しました。

<template>
  <h1>This is an about page</h1>
</template>

実行イメージ



ページのトップへ戻る