Skip to content

Latest commit

 

History

History
72 lines (53 loc) · 1.83 KB

passing-props.md

File metadata and controls

72 lines (53 loc) · 1.83 KB

Passing props

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.

To decouple this component from the router use props:

❌ Coupled to $route

const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User }
  ]
})

👍 Decoupled with props

const User = {
  props: ['id'],
  template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
  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 router looks at the component and searches for props with the same name as the route.params. When a prop is found and its type is Number, String or not set, the param is passed as prop.

Object mode

When props is an object, this will be set as the component props as-is.

const router = new VueRouter({
  routes: [
    { path: '/user/first-one', component: User, props: {id: '1' } }
  ]
})

Function mode

You can create a function that returns props. This allows you to mix static values and values based on the route.

const router = new VueRouter({
  routes: [
    { path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) }
  ]
})

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. Tip: If you need to set props based on route and state create a wrapper component.

For advanced usage, checkout the example.