Skip to content

Defining Routes and RouterView

With the conceptual foundation in place, it’s time to define routes and wire up Vue Router.

Routes are defined in src/router/index.ts as an array of route records. Each record maps a path to a component:

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: '/add',
name: 'add',
component: () => import('../views/AddPersonView.vue'),
},
{
path: '/edit/:id',
name: 'edit',
component: () => import('../views/EditPersonView.vue'),
},
{
path: '/:id',
name: 'person',
component: () => import('../views/PersonDetailView.vue'),
},
],
})
export default router

The () => import(...) syntax is lazy loading — the view’s JavaScript is only downloaded when a user first navigates to that route. This keeps the initial page load small.

The name field is optional but useful — it lets you navigate by name instead of hardcoding paths.

createWebHistory() uses the browser’s History API — URLs look like /add and /edit/abc. This requires server configuration for production (the server must serve index.html for all paths). Azure Static Web Apps handles this automatically.

createWebHashHistory() adds a # to URLs — /#!/add. No server configuration needed, but URLs look less clean.

In src/main.ts, install the router with .use():

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import router from './router'
import App from './App.vue'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')

The router must be installed before app.mount().

<RouterView> is the placeholder where the matched view component renders. It goes in App.vue:

App.vue
<template>
<nav>
<!-- navigation links -->
</nav>
<main>
<RouterView />
</main>
</template>

When the URL is /, HomeView renders inside <RouterView>. When it’s /add, AddPersonView renders there instead. The nav and <main> wrapper stay.

  1. Open src/router/index.ts in your project.
  2. Add a route for /about that renders a new AboutView.vue (create a minimal view with a heading).
  3. Confirm that visiting http://localhost:5173/about shows your new view.
  4. Add name: 'about' to the route record.
  • Route records map path to component in createRouter({ routes: [...] }).
  • () => import(...) lazy-loads a view — download only happens when the route is first visited.
  • createWebHistory() uses clean URLs; requires the server to serve index.html for all routes.
  • Install the router with app.use(router) in main.ts.
  • <RouterView> in the template is where matched views render.