Passing Props to Route Components

Watch a free video lesson on Vue School

Using $route in your component creates a tight coupling with the route which limits the flexibility of the component as it can only be used on certain URLs. While this is not necessarily a bad thing, we can decouple this behavior with a props option:

We can replace

  1. const User = {
  2. template: '<div>User {{ $route.params.id }}</div>'
  3. }
  4. const routes = [{ path: '/user/:id', component: User }]

with

  1. const User = {
  2. // make sure to add a prop named exactly like the route param
  3. props: ['id'],
  4. template: '<div>User {{ id }}</div>'
  5. }
  6. const routes = [{ path: '/user/:id', component: User, props: true }]

This allows you to use the component anywhere, which makes the component easier to reuse and test.

Boolean mode

When props is set to true, the route.params will be set as the component props.

Named views

For routes with named views, you have to define the props option for each named view:

  1. const routes = [
  2. {
  3. path: '/user/:id',
  4. components: { default: User, sidebar: Sidebar },
  5. props: { default: true, sidebar: false }
  6. }
  7. ]

Object mode

When props is an object, this will be set as the component props as-is. Useful for when the props are static.

  1. const routes = [
  2. {
  3. path: '/promotion/from-newsletter',
  4. component: Promotion,
  5. props: { newsletterPopup: false }
  6. }
  7. ]

Function mode

You can create a function that returns props. This allows you to cast parameters into other types, combine static values with route-based values, etc.

  1. const routes = [
  2. {
  3. path: '/search',
  4. component: SearchUser,
  5. props: route => ({ query: route.query.q })
  6. }
  7. ]

The URL /search?q=vue would pass {query: 'vue'} as props to the SearchUser component.

Try to keep the props function stateless, as it’s only evaluated on route changes. Use a wrapper component if you need state to define the props, that way vue can react to state changes.

For advanced usage, check out the example.