Router Basics

Back

Loading concept...

πŸš€ Vue Router Basics: Your App’s GPS System

Imagine you’re in a giant shopping mall. Without a map or signs, you’d be lost! Vue Router is like the mall’s navigation systemβ€”it tells your Vue app which β€œroom” (page) to show based on where the visitor wants to go.


🌟 The Big Picture

Think of your Vue app as a house with many rooms:

  • The living room is your Home page
  • The kitchen is your About page
  • The bedroom is your Profile page

Vue Router is the magic doorman who:

  1. Knows which room you want to visit
  2. Opens the right door
  3. Shows you exactly what’s inside

Without Vue Router, your house would have only ONE room. Boring! 😴


πŸ“¦ Router Installation

What Is It?

Installing Vue Router is like hiring that magic doorman for your house. You can’t navigate between rooms without him!

How To Do It

Step 1: Install the package

npm install vue-router@4

That’s it! You just hired your doorman. πŸŽ‰

Step 2: Create the router file

Create a new file called router/index.js:

import { createRouter, createWebHistory }
  from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: []
})

export default router

Step 3: Tell Vue to use it

In your main.js:

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

createApp(App)
  .use(router)
  .mount('#app')

🎯 Real-Life Example

It’s like downloading a map app on your phone. First you install it, then you open it, then you can navigate anywhere!


πŸ—ΊοΈ Creating Routes

What Are Routes?

Routes are directions that tell Vue Router: β€œWhen someone visits THIS address, show THAT page.”

The Simple Version

const routes = [
  {
    path: '/',
    component: Home
  },
  {
    path: '/about',
    component: About
  }
]

🧩 Breaking It Down

Part What It Means
path The URL address (like /about)
component The page to show

🎯 Real-Life Example

Think of a restaurant menu:

  • Path = β€œBurger” (what you order)
  • Component = The actual burger that arrives
// Full example with imports
import Home from './views/Home.vue'
import About from './views/About.vue'
import Contact from './views/Contact.vue'

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
  { path: '/contact', component: Contact }
]

Every route is a promise: β€œVisit this URL, see this page!”


βš™οΈ Router Configuration

What Is Configuration?

Configuration is setting up the rules for how your doorman behaves. Does he remember where you’ve been? Does he use clean URLs?

The Main Options

const router = createRouter({
  // How URLs look and work
  history: createWebHistory(),

  // All your routes
  routes: routes
})

πŸ”‘ History Modes

1. Web History (Clean URLs) ✨ Recommended!

history: createWebHistory()
// URLs look like: /about, /contact

2. Hash History (Has # in URL)

history: createWebHashHistory()
// URLs look like: /#/about, /#/contact

🎯 Which Should You Use?

Mode URL Example Best For
Web History /about Most apps
Hash History /#/about Simple hosting

Full Configuration Example

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

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})

export default router

πŸ“Ί RouterView Component

What Is RouterView?

<RouterView> is like a TV screen in your house. Whatever β€œchannel” (route) you’re on, the TV displays that content.

How It Works

<template>
  <div id="app">
    <header>My App</header>

    <!-- πŸ‘‡ This is the magic TV screen! -->
    <RouterView />

    <footer>Β© 2024</footer>
  </div>
</template>

🎯 Visual Explanation

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚       HEADER            β”‚  ← Always visible
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                         β”‚
β”‚     <RouterView />      β”‚  ← Changes based on URL!
β”‚                         β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚       FOOTER            β”‚  ← Always visible
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

When you visit /about:

  • Header stays the same
  • RouterView shows the About page
  • Footer stays the same

When you visit /contact:

  • Header stays the same
  • RouterView shows the Contact page
  • Footer stays the same

🎬 Think Of It Like This

RouterView is the movie screen at a cinema. The seats, walls, and popcorn stand stay the sameβ€”but the movie (content) changes!


πŸ”— RouterLink Component

What Is RouterLink?

<RouterLink> is a magic button that teleports visitors to different pages WITHOUT refreshing the whole app. It’s much faster than regular links!

Basic Usage

<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
<RouterLink to="/contact">Contact</RouterLink>

Why Not Use Regular Links?

Regular <a> tag <RouterLink>
Refreshes whole page 🐒 Instant switch ⚑
Loses app state Keeps everything
Slow Super fast

🎯 Real-Life Example

Regular link = Taking a taxi to a new store (slow, starts over)

RouterLink = Walking through a door in a mall (instant, you’re still in the mall!)

Full Navigation Example

<template>
  <nav>
    <RouterLink to="/">🏠 Home</RouterLink>
    <RouterLink to="/about">ℹ️ About</RouterLink>
    <RouterLink to="/contact">πŸ“§ Contact</RouterLink>
  </nav>
</template>

Dynamic Routes

You can also use variables:

<RouterLink :to="`/user/${userId}`">
  View Profile
</RouterLink>

🎨 Active Link Styling

What Is Active Link Styling?

When you’re on a page, the link to that page should look differentβ€”like a glowing button saying β€œYou are HERE!”

How Vue Router Helps

Vue Router automatically adds special classes to active links:

Class When It’s Added
router-link-active Current route matches
router-link-exact-active Exact match only

Basic CSS Styling

/* Style for active links */
.router-link-active {
  color: blue;
  font-weight: bold;
}

/* Style for exact matches */
.router-link-exact-active {
  color: green;
  border-bottom: 2px solid green;
}

Custom Class Names

Want your own class names? Easy!

<RouterLink
  to="/about"
  active-class="my-active"
  exact-active-class="my-exact-active"
>
  About
</RouterLink>
.my-active {
  background: yellow;
}
.my-exact-active {
  background: gold;
  transform: scale(1.1);
}

🎯 Visual Example

Navigation Bar:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Home   [About]   Contact        β”‚
β”‚          ↑                       β”‚
β”‚   This one glows because         β”‚
β”‚   we're on the About page!       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Complete Styled Navigation

<template>
  <nav class="navbar">
    <RouterLink to="/" class="nav-link">
      Home
    </RouterLink>
    <RouterLink to="/about" class="nav-link">
      About
    </RouterLink>
  </nav>
</template>

<style>
.nav-link {
  padding: 10px 20px;
  color: gray;
}

.nav-link.router-link-exact-active {
  color: white;
  background: #42b983;
  border-radius: 5px;
}
</style>

πŸ—ΊοΈ Putting It All Together

Here’s a complete mini-app using everything you learned:

graph TD A["User Types URL"] --> B{Vue Router} B --> C["Finds Matching Route"] C --> D["Loads Component"] D --> E["Shows in RouterView"] E --> F["User Sees Page!"]

Complete Example

router/index.js

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

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})

export default router

App.vue

<template>
  <div id="app">
    <nav>
      <RouterLink to="/">Home</RouterLink>
      <RouterLink to="/about">About</RouterLink>
    </nav>

    <RouterView />
  </div>
</template>

<style>
.router-link-exact-active {
  font-weight: bold;
  color: #42b983;
}
</style>

πŸŽ‰ Quick Summary

Concept What It Does One-Line Example
Installation Adds router to your app npm install vue-router@4
Routes Maps URLs to pages { path: '/', component: Home }
Configuration Sets up router rules createRouter({ history, routes })
RouterView Displays current page <RouterView />
RouterLink Navigation without refresh <RouterLink to="/">
Active Styling Highlights current link .router-link-active { }

πŸš€ You Did It!

You now understand Vue Router basics! Think of it like this:

🏠 Your app is a house πŸšͺ Routes are doors to different rooms 🧭 Router is the GPS that knows where you want to go πŸ“Ί RouterView is the TV showing current content πŸ”— RouterLink is the teleporter between rooms 🎨 Active styling is the β€œYou Are Here” marker

Now go build something amazing! 🌟

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.