Route Features

Back

Loading concept...

πŸ—ΊοΈ 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 of component when 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 &#35;40;named&#35;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 &#35;40;alias&#35;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.matched to 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! πŸš€

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.