Blog>
Snippets

Passing Props to Route Components in Vue.js 3

Demonstrating how to pass props to route components in Vue.js 3, enabling the reuse of components with different data for various routes.
// 1. Define your route components
const User = {
  template: '<div>User {{ $route.params.id }}</div>',
  props: ['id'] // define props
};

// 2. Define the routes with props configuration
const routes = [
  { path: '/user/:id', component: User, props: true }, // pass route.params to props
];

// 3. Create the VueRouter instance and pass the `routes` option
const router = VueRouter.createRouter({
  history: VueRouter.createWebHashHistory(),
  routes
});

// 4. Create and mount the root instance
const app = Vue.createApp({});
app.use(router);
app.mount('#app');
This code sets up a Vue 3 application with Vue Router. It demonstrates how to define route components that accept route parameters as props and configure the router to pass those parameters automatically.
// Vue component using props
const UserProfile = {
  template: '<div>User Profile for: {{ username }}</div>',
  props: {
    username: String
  }
};

// Route definitions using function mode to pass props
const routes = [
  {
    path: '/profile/:username',
    component: UserProfile,
    // Pass route params as props using a function
    props: route => ({ username: route.params.username })
  }
];

// VueRouter instance
const router = VueRouter.createRouter({
  history: VueRouter.createWebHashHistory(),
  routes
});

// Vue app initialization
const app = Vue.createApp({});
app.use(router);
app.mount('#app');
This code demonstrates how to use a function mode to pass route params to a component as props, allowing more complex logic for determining what props to pass based on the current route.