Skip to content

Commit 19a3782

Browse files
committed
docs: data hook promise sugar
1 parent 802d743 commit 19a3782

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

docs/en/pipeline/data.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ Called on an incoming component during the activation phase, after the `activate
1414
- `resolve(data)` -> `transition.next(data)`
1515
- `reject(reason)` -> `transition.abort(reason)`
1616

17+
- or, return an Object containing Promises. See [Promise sugar](#promise-sugar) below.
18+
1719
### Details
1820

1921
The `data` transition hook is called immediately after the `activate` hook is resolved, and right before the view switching is executed. The entering component gets a **`$loadingRouteData`** meta property, which starts with value `false` and set to `true` when the `data` hook is resolved. This property can be used to display a loading state for the entering component.
@@ -107,3 +109,32 @@ Using `$loadingRouteData` in templates:
107109
</div>
108110
</div>
109111
```
112+
113+
### Promise Sugar
114+
115+
The parallel data fetching example above requires us to leverage `Promise.all` to combine multiple Promises into a single one, and the desturcturing and formatting is still a bit cumbersome. `vue-router` provides a syntax sugar which allows you to return an Object containing Promises (it can contain non-Promise fields too, of course). Here's the same example using the syntax sugar and ES6:
116+
117+
``` js
118+
route: {
119+
data: ({ to: { params: { userId }}}) => ({
120+
user: userService.get(userId),
121+
post: postsService.getForUser(userId)
122+
})
123+
}
124+
```
125+
126+
The router will set the component's `user` and `post` fields to the corresponding Promises' resolved values when they are resolved. `$loadingRouteData` will be set to `false` when all Promises have been resolved.
127+
128+
Equivalent in ES5:
129+
130+
``` js
131+
route: {
132+
data: function (transition) {
133+
var userId = transition.to.params.userId
134+
return {
135+
user: userService.get(userId),
136+
post: postsService.getForUser(userId)
137+
}
138+
}
139+
}
140+
```

0 commit comments

Comments
 (0)