From 848f125dfc3fdd625678ab4ab8df0b702553c20d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Radam=C3=A9s=20Roriz?= Date: Mon, 7 Dec 2020 16:29:42 -0300 Subject: [PATCH] docs(dynamic-matching): add optional param on docs --- docs/guide/essentials/dynamic-matching.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/guide/essentials/dynamic-matching.md b/docs/guide/essentials/dynamic-matching.md index 15bcdfca4..bcd9d8081 100644 --- a/docs/guide/essentials/dynamic-matching.md +++ b/docs/guide/essentials/dynamic-matching.md @@ -35,9 +35,26 @@ You can have multiple dynamic segments in the same route, and they will map to c | ----------------------------- | ------------------- | -------------------------------------- | | /user/:username | /user/evan | `{ username: 'evan' }` | | /user/:username/post/:post_id | /user/evan/post/123 | `{ username: 'evan', post_id: '123' }` | +| /user/:username/post/:post_id?| /user/evan/post | `{ username: 'evan' }` | In addition to `$route.params`, the `$route` object also exposes other useful information such as `$route.query` (if there is a query in the URL), `$route.hash`, etc. You can check out the full details in the [API Reference](../../api/#the-route-object). +## Optional Param + +often we will need to map the same route with and without param to the same component. For example, we may have a `User` component which should be rendered for all users or a specific ID. In `vue-router` we can use a dynamic segment in the path to achieve that: +```js +const User = { + template: '
User
' +} + +const router = new VueRouter({ + routes: [ + // dynamic segments start with a colon + { path: '/user/:id?', component: User } + ] +}) +``` + ## Reacting to Params Changes One thing to note when using routes with params is that when the user navigates from `/user/foo` to `/user/bar`, **the same component instance will be reused**. Since both routes render the same component, this is more efficient than destroying the old instance and then creating a new one. **However, this also means that the lifecycle hooks of the component will not be called**.