0
0
VueHow-ToBeginner · 3 min read

How to Create Dynamic Routes in Vue with Vue Router

In Vue, you create dynamic routes by defining route paths with parameters using : in the path, like /user/:id. Vue Router captures the dynamic part as a parameter accessible in your component via $route.params.
📐

Syntax

Dynamic routes use a colon : before a segment in the path to mark it as a variable. This variable can then be accessed inside the component.

  • path: Defines the URL pattern with dynamic segments.
  • component: The Vue component to render for this route.
  • $route.params: Object holding the dynamic values from the URL.
javascript
const routes = [
  {
    path: '/user/:id',
    component: UserProfile
  }
];
💻

Example

This example shows a Vue app with a dynamic route /user/:id. The UserProfile component reads the id from the URL and displays it.

javascript
import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';

const UserProfile = {
  template: `<div>User ID: {{ userId }}</div>`,
  computed: {
    userId() {
      return this.$route.params.id;
    }
  }
};

const routes = [
  { path: '/user/:id', component: UserProfile }
];

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

const app = createApp({});
app.use(router);
app.mount('#app');
Output
When visiting /user/123, the page shows: User ID: 123
⚠️

Common Pitfalls

Common mistakes when creating dynamic routes include:

  • Forgetting the colon : before the parameter name in the path.
  • Trying to access $route.params before the router is ready.
  • Not handling cases where the parameter might be missing or invalid.

Always ensure your route path uses : and your component accesses $route.params safely.

javascript
/* Wrong: Missing colon, so no dynamic parameter */
const routesWrong = [
  { path: '/user/id', component: UserProfile }
];

/* Right: Colon marks dynamic parameter */
const routesRight = [
  { path: '/user/:id', component: UserProfile }
];
📊

Quick Reference

ConceptDescriptionExample
Dynamic segmentPart of path that changes, marked with colon/user/:id
Access paramsUse $route.params inside componentthis.$route.params.id
Router setupCreate router with routes arraycreateRouter({ history, routes })
ComponentVue component rendered for routeUserProfile

Key Takeaways

Use a colon before a path segment to create a dynamic route parameter in Vue Router.
Access dynamic parameters inside components via this.$route.params.
Always define your routes correctly with dynamic segments to avoid routing errors.
Test your dynamic routes by visiting URLs with different parameter values.
Handle missing or invalid parameters gracefully in your components.