Skip to content

Commit 75a18dc

Browse files
committed
docs: add function example to props
Close #2493
1 parent b717bf2 commit 75a18dc

File tree

1 file changed

+24
-12
lines changed

1 file changed

+24
-12
lines changed

Diff for: docs/guide/essentials/passing-props.md

+24-12
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,24 @@
22

33
<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>
44

5-
65
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.
76

87
To decouple this component from the router use option `props`:
98

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

12-
``` js
11+
```js
1312
const User = {
1413
template: '<div>User {{ $route.params.id }}</div>'
1514
}
1615
const router = new VueRouter({
17-
routes: [
18-
{ path: '/user/:id', component: User }
19-
]
16+
routes: [{ path: '/user/:id', component: User }]
2017
})
2118
```
2219

2320
**Decouple it by using `props`**
2421

25-
``` js
22+
```js
2623
const User = {
2724
props: ['id'],
2825
template: '<div>User {{ id }}</div>'
@@ -34,8 +31,15 @@ const router = new VueRouter({
3431
// for routes with named views, you have to define the `props` option for each named view:
3532
{
3633
path: '/user/:id',
37-
components: { default: User, sidebar: Sidebar },
38-
props: { default: true, sidebar: false }
34+
components: {
35+
default: User,
36+
sidebar: Sidebar
37+
},
38+
props: {
39+
default: true,
40+
// function mode, more about it below
41+
sidebar: route => ({ search: route.query.q })
42+
}
3943
}
4044
]
4145
})
@@ -51,10 +55,14 @@ When `props` is set to `true`, the `route.params` will be set as the component p
5155

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

54-
``` js
58+
```js
5559
const router = new VueRouter({
5660
routes: [
57-
{ path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } }
61+
{
62+
path: '/promotion/from-newsletter',
63+
component: Promotion,
64+
props: { newsletterPopup: false }
65+
}
5866
]
5967
})
6068
```
@@ -63,10 +71,14 @@ const router = new VueRouter({
6371

6472
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.
6573

66-
``` js
74+
```js
6775
const router = new VueRouter({
6876
routes: [
69-
{ path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) }
77+
{
78+
path: '/search',
79+
component: SearchUser,
80+
props: route => ({ query: route.query.q })
81+
}
7082
]
7183
})
7284
```

0 commit comments

Comments
 (0)