~ 1 min read

How to Pass Vue Route Params as Component Props

If you’re using vues router to link to dynamic URLs you may get stuck wondering why your props on router-links aren’t being sent to your components. Vue’s router doesn’t support sending props directly. So you can’t do something like this:

<router-link
  class="..."
  :to="{
     path: `/user/edit/`,
     id=id
   }"
   >Edit
</router-link>

Here the id prop will never get passed in routers default configuration. Instead you need to configure each of your routes to pass the route params as props like so:

<router-link
  class="..."
  :to="{
     path: `/user/edit/${id}`
   }"
   >Edit
</router-link>
const UserEdit = {
  props: ['id'],
  template: '<div>Edit User {{ id }}</div>'
}

const routes = [{ 
	path: '/user/edit/:id', 
  component: UserEdit, 
  props: true 
}]

This way, the id comes through as a prop to our component without an issue. Router allows this to avoid tight coupling between components and route params.

Object Mode

It’s also possible to define the props value for a route to be an object or function like this:

const routes = [{ 
	path: '/user/edit/:id', 
  component: UserEdit, 
  props: {
		sidebar: true
	} 
}]
const routes = [{ 
	path: '/search', 
  component: UserSearch, 
  props: {
		sidebar: route => ({ query: route.query.q })
	} 
}]

For more info check out vues router documentation:

https://router.vuejs.org/guide/essentials/passing-props.html

Subscribe for Exclusives

My monthly newsletter shares exclusive articles you won't find elsewhere, tools and code. No spam, unsubscribe any time.