}
},
created() {
- // fetch the data when the view is created and the data is
- // already being observed
- this.fetchData()
- },
- watch: {
- // call again the method if the route changes
- $route: 'fetchData',
+ // watch the params of the route to fetch the data again
+ this.$watch(
+ () => this.$route.params,
+ () => {
+ this.fetchData()
+ },
+ // fetch the data when the view is created and the data is
+ // already being observed
+ { immediate: true }
+ )
},
methods: {
fetchData() {
```js
const User = {
- template: '<div>User</div>'
+ template: '<div>User</div>',
}
// these are passed to `createRouter`
const routes = [
// dynamic segments start with a colon
- { path: '/user/:id', component: User }
+ { path: '/user/:id', component: User },
]
```
```js
const User = {
- template: '<div>User {{ $route.params.id }}</div>'
+ template: '<div>User {{ $route.params.id }}</div>',
}
```
One thing to note when using routes with params is that when the user navigates from `/user/johnny` to `/user/jolyne`, **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**.
-To react to params changes in the same component, you can simply watch the `$route` object:
+To react to params changes in the same component, you can simply watch anything on the `$route` object, in this scenario, the `$route.params`:
```js
const User = {
template: '...',
- watch: {
- $route(to, from) {
- // react to route changes...
- }
- }
+ created() {
+ this.$watch(
+ () => this.$route.params,
+ (toParams, previousParams) => {
+ // react to route changes...
+ }
+ )
+ },
}
```
```js
const User = {
template: '...',
- beforeRouteUpdate(to, from, next) {
+ async beforeRouteUpdate(to, from) {
// react to route changes...
- // don't forget to call next()
- }
+ this.userData = await fetchUser(to.params.id)
+ },
}
```