#vue #javascript #frontend

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')

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

  1. Create a navigation bar with links: ā€œHomeā€, ā€œContactā€.
  2. On the ā€œContactā€ page, add a form (from Day 4).
  3. On form submit, redirect the user back to ā€œHomeā€ programmatically.
    • Hint: Use useRouter() composable.

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.