Damian Helme
Damian Helme

Reputation: 1121

Vuejs component reuse on navigation change - clarification sought

In the following example, if the user navigates from /user/foo to /another_page and then to /user/bar, will the User component be reused?

const User = {
   template: '<div>User</div>'
}

const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User }
  ]
})

The Vue Router manuals says ...

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.

Dynamic Route Matching

... but it's not clear whether the component is only reused when there are no intermediary navigation steps. Is there any documentation that discusses component reuse in this kind of detail?

Thanks!

Upvotes: 2

Views: 300

Answers (1)

Adam Orłowski
Adam Orłowski

Reputation: 4464

If you navigate from /user/foo to /user/bar then the component will be reused. This is often used when displaying product page for example. Note that there are ways to rebuild component if it is needed.

If you will navigate from /user/foo to /another_page and then navigate to /user/bar then your component will be destroyed when leaving to /another_page and created when navigating to /user/bar.

To sum up:

/user/foo -> /another_page - component gets destroyed

/user/foo -> /user/bar - component will be reused

Upvotes: 3

Related Questions