Defining Routes and RouterView
With the conceptual foundation in place, it’s time to define routes and wire up Vue Router.
Defining route records
Section titled “Defining route records”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 routerThe () => 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.
History modes
Section titled “History modes”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.
Installing the router
Section titled “Installing the router”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>
Section titled “<RouterView>”<RouterView> is the placeholder where the matched view component renders. It goes in 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.
Exercise
Section titled “Exercise”- Open
src/router/index.tsin your project. - Add a route for
/aboutthat renders a newAboutView.vue(create a minimal view with a heading). - Confirm that visiting
http://localhost:5173/aboutshows your new view. - Add
name: 'about'to the route record.
- Route records map
pathtocomponentincreateRouter({ routes: [...] }). () => import(...)lazy-loads a view — download only happens when the route is first visited.createWebHistory()uses clean URLs; requires the server to serveindex.htmlfor all routes.- Install the router with
app.use(router)inmain.ts. <RouterView>in the template is where matched views render.