πΊοΈ Vue Router - Route Features
The Map of Your App Kingdom
Imagine youβre building a magical kingdom (your Vue app). Your kingdom has many rooms - a throne room, a treasure vault, a library. But how do visitors know where to go? They need signs, secret passages, and shortcuts!
Vue Routerβs Route Features are exactly that - smart signs and magical doors that help visitors navigate your kingdom perfectly.
π·οΈ Named Routes
What Are They?
Instead of remembering long paths like /users/profile/settings, you give routes friendly names. Itβs like calling your friend βAlexβ instead of their full address!
Simple Example
// Define a route with a name
const routes = [
{
path: '/user/profile',
name: 'profile', // π This is the name!
component: UserProfile
}
]
Why Use Names?
// β Hard way - using path (can break if path changes)
router.push('/user/profile')
// β
Easy way - using name (always works!)
router.push({ name: 'profile' })
With Parameters
// Route definition
{
path: '/user/:id',
name: 'user',
component: User
}
// Navigate with params
router.push({
name: 'user',
params: { id: 123 }
})
// Goes to: /user/123
In Templates
<router-link :to="{ name: 'profile' }">
My Profile
</router-link>
π― Remember: Names are like nicknames - easier to remember and wonβt break when paths change!
ποΈ Named Views
What Are They?
Sometimes one page needs to show multiple components at once - like a dashboard with sidebar, header, and main content. Named Views let you do this!
The Analogy
Think of a TV with picture-in-picture. You have the main show, but also a smaller window showing something else. Named Views work the same way!
Basic Setup
<!-- In your template -->
<router-view></router-view> <!-- main -->
<router-view name="sidebar"></router-view> <!-- sidebar -->
<router-view name="header"></router-view> <!-- header -->
Route Configuration
const routes = [
{
path: '/dashboard',
components: { // π Note: "components" (plural!)
default: MainContent,
sidebar: Sidebar,
header: Header
}
}
]
graph TD A["/dashboard"] --> B["default: MainContent"] A --> C["sidebar: Sidebar"] A --> D["header: Header"]
π― Key Point: Use
components(plural) instead ofcomponentwhen using named views!
πͺ Nested Routes
What Are They?
Pages inside pages! Like Russian nesting dolls πͺ. A User page might have Profile, Posts, and Settings as sub-pages.
Real-World Analogy
Think of a house:
- House =
/user - Bedroom =
/user/profile - Kitchen =
/user/posts - Bathroom =
/user/settings
Parent Component
<!-- User.vue -->
<template>
<div>
<h1>User Section</h1>
<nav>
<router-link to="/user/profile">Profile</router-link>
<router-link to="/user/posts">Posts</router-link>
</nav>
<!-- Child routes render here! π -->
<router-view></router-view>
</div>
</template>
Route Configuration
const routes = [
{
path: '/user',
component: User,
children: [ // π Nested routes go here!
{
path: 'profile', // becomes /user/profile
component: UserProfile
},
{
path: 'posts', // becomes /user/posts
component: UserPosts
}
]
}
]
graph TD A["/user"] --> B["/user/profile"] A --> C["/user/posts"] A --> D["/user/settings"] B --> E["UserProfile Component"] C --> F["UserPosts Component"]
π― Notice: Child paths donβt start with
/. Vue Router adds them automatically!
βͺοΈ Route Redirect
What Is It?
Auto-forward visitors from one path to another. Like a mailman who knows you moved and delivers mail to your new address!
Simple Redirect
const routes = [
{
path: '/home',
redirect: '/' // Go to / instead
}
]
Redirect to Named Route
{
path: '/old-profile',
redirect: { name: 'profile' } // Use route name
}
Dynamic Redirect (with function)
{
path: '/search/:query',
redirect: to => {
// `to` contains route info
return {
path: '/results',
query: { q: to.params.query }
}
}
}
// /search/cats β /results?q=cats
Keep Params
{
path: '/user/:id/profile',
redirect: to => {
return `/profile/${to.params.id}`
}
}
graph LR A["/home"] -->|redirect| B["/"] C["/old-profile"] -->|redirect| D["profile #40;named#41;"] E["/search/cats"] -->|redirect| F["/results?q=cats"]
π― Use Case: Perfect for when you rename URLs but want old bookmarks to still work!
π Route Alias
What Is It?
Two doors, same room! An alias gives your route an extra address. Both URLs show the same content.
The Difference from Redirect
| Feature | Redirect | Alias |
|---|---|---|
| URL changes? | Yes β | No β |
| Same content? | Yes β | Yes β |
| Browser history | Goes to new URL | Stays at alias URL |
Simple Alias
{
path: '/dashboard',
component: Dashboard,
alias: '/home' // π Extra entrance!
}
// Both /dashboard AND /home show Dashboard
Multiple Aliases
{
path: '/users',
component: Users,
alias: ['/people', '/members', '/team']
// All 4 paths show the same component!
}
Alias with Params
{
path: '/user/:id',
component: User,
alias: '/person/:id'
}
// /user/123 AND /person/123 both work!
graph TD A["/dashboard"] --> D["Dashboard Component"] B["/home #40;alias#41;"] --> D C["URL stays as /home"] --> D
π― Use Case: Great for SEO when you want multiple URLs for the same page without redirecting!
π Route Meta Fields
What Are They?
Secret notes attached to routes! Extra information you can read later - like sticky notes on doors telling guards who can enter.
Common Uses
- π Check if route needs login
- π Track page analytics
- π¨ Set page title
- π₯ Define user permissions
Basic Meta
{
path: '/admin',
component: Admin,
meta: {
requiresAuth: true,
title: 'Admin Panel'
}
}
Reading Meta in Navigation Guard
router.beforeEach((to, from) => {
// Check meta field
if (to.meta.requiresAuth) {
// Is user logged in?
if (!isLoggedIn()) {
return { name: 'login' }
}
}
})
Meta on Nested Routes
{
path: '/user',
component: User,
meta: { requiresAuth: true },
children: [
{
path: 'profile',
component: Profile,
meta: { title: 'Profile' } // Own meta
}
]
}
Accessing All Matched Meta
router.beforeEach((to, from) => {
// to.matched = array of all matched routes
// Check if ANY matched route requires auth
const needsAuth = to.matched.some(
record => record.meta.requiresAuth
)
if (needsAuth && !isLoggedIn()) {
return '/login'
}
})
graph TD A["Route: /admin"] --> B["meta: requiresAuth"] A --> C["meta: title"] D["Navigation Guard"] --> E{"Check meta.requiresAuth"} E -->|true| F["Check if logged in"] E -->|false| G["Allow navigation"] F -->|Not logged in| H["Redirect to login"] F -->|Logged in| G
π― Power Tip: Use
to.matchedto check meta from parent routes too!
πͺ Quick Summary
| Feature | What It Does | Example |
|---|---|---|
| Named Routes | Give routes nicknames | name: 'profile' |
| Named Views | Multiple components per route | components: { default, sidebar } |
| Nested Routes | Pages inside pages | children: [...] |
| Redirect | Auto-forward to new URL | redirect: '/new' |
| Alias | Extra URL, same content | alias: '/shortcut' |
| Meta | Attach custom data | meta: { auth: true } |
π You Did It!
You now know all the secret passages and magic doors in Vue Router!
- Named Routes = Easy nicknames π·οΈ
- Named Views = Multi-window layouts ποΈ
- Nested Routes = Pages in pages πͺ
- Redirect = Auto-forwarding βͺοΈ
- Alias = Multiple entrances π
- Meta = Secret notes π
Go build something amazing! π
