Day 10: Vue Router Fundamentals
Welcome to Day 10! So far, weāve built āSingle Viewā apps. But real apps have pages (Home, About, Profile). We handle this with Vue Router.
Installation
If you didnāt select āYesā for Router during setup (Day 1), install it now:
npm install vue-router@4
Router Setup
We need to create a router instance and define our routes.
src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'
const router = createRouter({
// Use HTML5 History mode (clean URLs)
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
component: AboutView
}
]
})
export default router
src/main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router' // <--- Import it
const app = createApp(App)
app.use(router) // <--- Use it
app.mount('#app')
Building the UI: <RouterView> & <RouterLink>
In your App.vue, you need two things:
1. Where to render the page?
Use the <RouterView /> component. This is a placeholder. When you visit /, HomeView appears here. When you visit /about, AboutView replaces it.
2. How to navigate?
Donāt use <a href="...">! That triggers a full page reload.
Use <RouterLink to="...">.
App.vue
<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
</script>
<template>
<header>
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
</nav>
</header>
<RouterView />
</template>
<style scoped>
/* RouterLink automatically gets this class when active */
.router-link-active {
font-weight: bold;
color: green;
}
</style>
Lazy Loading (Performance)
For large apps, you donāt want to load every pageās JavaScript upfront. You can lazy-load routes.
{
path: '/about',
name: 'about',
// Only load this file when user visits /about
component: () => import('../views/AboutView.vue')
}
Challenge for Day 10
- Create a navigation bar with links: āHomeā, āContactā.
- On the āContactā page, add a form (from Day 4).
- On form submit, redirect the user back to āHomeā programmatically.
- Hint: Use
useRouter()composable.
- Hint: Use
Solution:
<!-- views/ContactView.vue -->
<script setup lang="ts">
import { useRouter } from 'vue-router'
const router = useRouter()
function sendMessage() {
// ... process form ...
alert('Message sent!')
// Redirect
router.push('/')
}
</script>
<template>
<h1>Contact Us</h1>
<button @click="sendMessage">Send</button>
</template>
Great work! You now have a multi-page app. Tomorrow, we explore dynamic URLs (like /user/123) and route guards.