Route Parameters

Back

Loading concept...

Vue Router - Route Parameters 🚀

The Magic Doors of Your Web House

Imagine you have a magic house with many doors. Each door leads to a different room. But here’s the cool part — some doors can change based on who wants to enter!

Your Website = Magic House
Routes = Doors
Parameters = Name Tags on Doors

🎯 What Are Route Parameters?

Think of it like this:

  • You have a door labeled “Bedroom”
  • But you have MANY bedrooms: Tom’s room, Sara’s room, Max’s room
  • Instead of making 100 separate doors, you make ONE smart door: “Bedroom/:name”

The :name is like a blank space where you write WHO the room belongs to!

graph TD A["User Types URL"] --> B{Which Door?} B -->|/user/tom| C["Tom's Page] B -->|/user/sara| D[Sara's Page"] B -->|/user/max| E[Max's Page]

1️⃣ Dynamic Route Matching

The Story of the Smart Door 🚪

Regular doors are boring. They only open to ONE place.

Regular Route:

{ path: '/about', component: About }

This ONLY works for /about. Nothing else.

Dynamic Route (The Smart Door):

{
  path: '/user/:id',
  component: User
}

See that :id? That’s a placeholder! It matches ANY value:

  • /user/123 ✅ Works!
  • /user/tom ✅ Works!
  • /user/pizza ✅ Works too!

Real Example

// In your router file
const routes = [
  {
    path: '/product/:productId',
    component: ProductDetail
  }
]

Now these ALL work:

  • /product/1 → Shows product #1
  • /product/shoes → Shows shoes
  • /product/abc123 → Shows abc123

Multiple Parameters 🎪

You can have MANY placeholders!

{
  path: '/user/:userId/post/:postId',
  component: UserPost
}

URL: /user/tom/post/42

  • :userId = “tom”
  • :postId = “42”

2️⃣ Route Parameters

What Gets Captured?

Every time someone visits your dynamic route, Vue Router captures what they typed.

URL Visited Parameter Name Value
/user/john :id “john”
/product/555 :productId “555”
/book/harry-potter :bookName “harry-potter”

The Rule Book 📖

  • Parameters start with : (colon)
  • They match ANYTHING until the next /
  • They become strings (even numbers!)
// Route definition
{ path: '/item/:id' }

// URL: /item/42
// :id = "42" (string, not number!)

Optional Parameters

Sometimes you want the door to work WITH or WITHOUT a name tag:

{
  path: '/user/:id?',
  component: User
}

The ? makes it optional!

  • /user ✅ Works (id is undefined)
  • /user/tom ✅ Works (id is “tom”)

3️⃣ Route Params Access

How to READ the Parameters 🔍

You opened the smart door. Now how do you know WHO came in?

Inside ANY component:

// Method 1: Composition API (Recommended)
import { useRoute } from 'vue-router'

export default {
  setup() {
    const route = useRoute()

    // Get the parameter!
    const userId = route.params.id

    console.log(userId) // "tom"
  }
}
// Method 2: Options API
export default {
  mounted() {
    // Access via this.$route
    console.log(this.$route.params.id)
  }
}

Inside the Template

<template>
  <div>
    <h1>Welcome, {{ $route.params.id }}!</h1>
  </div>
</template>

If URL is /user/sarah:

Welcome, sarah!

Watch for Changes! 👀

Here’s a SUPER important thing. When you go from /user/tom to /user/sara, the component DOESN’T reload. Same component, different data!

import { useRoute, watch } from 'vue-router'

export default {
  setup() {
    const route = useRoute()

    // Watch for param changes!
    watch(
      () => route.params.id,
      (newId, oldId) => {
        console.log(`Changed from ${oldId} to ${newId}`)
        // Fetch new data here!
      }
    )
  }
}

4️⃣ Route Query Access

Parameters vs Query — What’s the Difference? 🤔

Think of a pizza order:

/pizza/large        ← Parameter (WHAT pizza)
/pizza/large?extra=cheese&drink=cola  ← Query (EXTRAS!)

Parameters = Main thing (part of the path) Query = Extra options (after the ?)

Reading Query Parameters

URL: /search?keyword=vue&page=2

import { useRoute } from 'vue-router'

export default {
  setup() {
    const route = useRoute()

    // Access query params
    const keyword = route.query.keyword  // "vue"
    const page = route.query.page        // "2"
  }
}

In the Template

<template>
  <div>
    <p>Searching for: {{ $route.query.keyword }}</p>
    <p>Page: {{ $route.query.page }}</p>
  </div>
</template>

Query vs Params — Quick Compare

Feature Params Query
Location In the path After ?
Required? Usually yes Optional
URL Look /user/tom /user?name=tom
Best For Main resource Filters, options

Complete Example 🎉

// Router setup
const routes = [
  {
    path: '/products/:category',
    component: Products
  }
]
// Products.vue
import { useRoute } from 'vue-router'

export default {
  setup() {
    const route = useRoute()

    // URL: /products/electronics?sort=price&order=asc

    const category = route.params.category
    // "electronics"

    const sortBy = route.query.sort
    // "price"

    const order = route.query.order
    // "asc"

    return { category, sortBy, order }
  }
}

🎨 The Big Picture

graph TD A["URL: /user/tom?active=true"] --> B["Vue Router"] B --> C{Extracts} C --> D["params.id = tom"] C --> E["query.active = true"] D --> F["Your Component"] E --> F F --> G["Use the Data!"]

🧠 Remember This!

  1. Dynamic routes use :paramName to match changing values
  2. route.params holds values from the URL path
  3. route.query holds values after the ?
  4. Watch params when they can change on the same component
  5. All values are strings — convert if needed!

💪 You Did It!

You now understand how Vue Router’s smart doors work. You can:

  • Create flexible routes with parameters
  • Read those parameters in your components
  • Use query strings for extra options

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.