How to Pass Props via Route in Vue: Simple Guide
In Vue, you can pass props to components via routes by setting
props: true in the route definition or by using a function to map route params to props. This allows the routed component to receive data as props directly from the URL or route configuration.Syntax
To pass props via route in Vue Router, add a props option to your route object. It can be:
- Boolean:
truepasses route params as props. - Object: Passes a static object as props.
- Function: Returns an object to map route params or query to props.
javascript
const routes = [ { path: '/user/:id', component: User, props: true // route params passed as props }, { path: '/about', component: About, props: { info: 'static info' } // static props }, { path: '/search', component: Search, props: route => ({ query: route.query.q }) // function mapping } ]
Example
This example shows a route passing the id param as a prop to the User component. The component then displays the id.
javascript
import { createRouter, createWebHistory } from 'vue-router' import { createApp, defineComponent } from 'vue' const User = defineComponent({ props: ['id'], template: `<div>User ID: {{ id }}</div>` }) const routes = [ { path: '/user/:id', component: User, props: true } ] const router = createRouter({ history: createWebHistory(), routes }) const app = createApp({}) app.use(router) app.mount('#app')
Output
When navigating to /user/42, the page shows: User ID: 42
Common Pitfalls
Common mistakes include:
- Not setting
props: trueor a function, so the component does not receive route params as props. - Trying to access route params via
this.$route.paramsinside the component instead of using props, which is less clean. - Passing props incorrectly as static objects when dynamic data is needed.
javascript
const routes = [ { path: '/user/:id', component: User, // Missing props: true, so 'id' is not passed as prop } ] // Correct way: const routesFixed = [ { path: '/user/:id', component: User, props: true } ]
Quick Reference
| Props Option | Description | Example Usage |
|---|---|---|
| true | Pass route params as props | props: true |
| Object | Pass static props | props: { name: 'Vue' } |
| Function | Map route to props dynamically | props: route => ({ id: route.params.id }) |
Key Takeaways
Set props: true in route to pass route params as props to components.
Use a function in props to customize which route data becomes props.
Passing props via routes keeps components clean and easier to test.
Avoid accessing route params directly inside components; prefer props.
Static props can be passed using an object in the route's props option.