Skip to content

Commit

Permalink
docs: add function example to props
Browse files Browse the repository at this point in the history
Close #2493
  • Loading branch information
posva committed Aug 8, 2020
1 parent b717bf2 commit 75a18dc
Showing 1 changed file with 24 additions and 12 deletions.
36 changes: 24 additions & 12 deletions docs/guide/essentials/passing-props.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,24 @@

<div class="vueschool"><a href="https://vueschool.io/lessons/how-to-pass-vue-router-params-as-props-to-components?friend=vuejs" target="_blank" rel="sponsored noopener" title="Learn how to pass props to route components with Vue School">Learn how to pass props to route components with a free lesson on Vue School</a></div>


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 option `props`:

**Instead of coupling to `$route`:**

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

**Decouple it by using `props`**

``` js
```js
const User = {
props: ['id'],
template: '<div>User {{ id }}</div>'
Expand All @@ -34,8 +31,15 @@ const router = new VueRouter({
// for routes with named views, you have to define the `props` option for each named view:
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
components: {
default: User,
sidebar: Sidebar
},
props: {
default: true,
// function mode, more about it below
sidebar: route => ({ search: route.query.q })
}
}
]
})
Expand All @@ -51,10 +55,14 @@ When `props` is set to `true`, the `route.params` will be set as the component p

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

``` js
```js
const router = new VueRouter({
routes: [
{ path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } }
{
path: '/promotion/from-newsletter',
component: Promotion,
props: { newsletterPopup: false }
}
]
})
```
Expand All @@ -63,10 +71,14 @@ const router = new VueRouter({

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.

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

0 comments on commit 75a18dc

Please sign in to comment.