|
| 1 | +# Passing props |
| 2 | + |
| 3 | +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. |
| 4 | + |
| 5 | +To decouple this component from the router use props: |
| 6 | + |
| 7 | +**❌ Coupled to $route** |
| 8 | + |
| 9 | +``` js |
| 10 | +const User = { |
| 11 | + template: '<div>User {{ $route.params.id }}</div>' |
| 12 | +} |
| 13 | +const router = new VueRouter({ |
| 14 | + routes: [ |
| 15 | + { path: '/user/:id', component: User } |
| 16 | + ] |
| 17 | +}) |
| 18 | +``` |
| 19 | + |
| 20 | +**👍 Decoupled with props** |
| 21 | + |
| 22 | +``` js |
| 23 | +const User = { |
| 24 | + props: ['id'], |
| 25 | + template: '<div>User {{ id }}</div>' |
| 26 | +} |
| 27 | +const router = new VueRouter({ |
| 28 | + routes: [ |
| 29 | + { path: '/user/:id', component: User, props: true } |
| 30 | + ] |
| 31 | +}) |
| 32 | +``` |
| 33 | + |
| 34 | +This allows you to use the component anywhere, which makes the component easier to reuse and test. |
| 35 | + |
| 36 | +### Boolean mode |
| 37 | + |
| 38 | +When props is set to true, the route.params will be set as the component props. |
| 39 | + |
| 40 | +### Object mode |
| 41 | + |
| 42 | +When props is an object, this will be set as the component props as-is. |
| 43 | +Useful for when the props are static. |
| 44 | + |
| 45 | +``` js |
| 46 | +const router = new VueRouter({ |
| 47 | + routes: [ |
| 48 | + { path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } } |
| 49 | + ] |
| 50 | +}) |
| 51 | +``` |
| 52 | + |
| 53 | +### Function mode |
| 54 | + |
| 55 | +You can create a function that returns props. |
| 56 | +This allows you to to cast the parameter to another type, combine static values with route-based values, etc. |
| 57 | + |
| 58 | +``` js |
| 59 | +const router = new VueRouter({ |
| 60 | + routes: [ |
| 61 | + { path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) } |
| 62 | + ] |
| 63 | +}) |
| 64 | +``` |
| 65 | + |
| 66 | +The url: `/search?q=vue` would pass `{query: "vue"}` as props to the SearchUser component. |
| 67 | + |
| 68 | +Try to keep the props function stateless, as it's only evaluated on route changes. |
| 69 | +Use a wrapper component if you need state to define the props, that way vue can react to state changes. |
| 70 | + |
| 71 | + |
| 72 | +For advanced usage, checkout the [example](https://github.com/vuejs/vue-router/blob/dev/examples/route-props/app.js). |
0 commit comments