Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue Single page app Router, what happens with the components when we change route?

Let's suppose I have a component called FirstPage, which is my default route, now FirstPage triggers an asynchronous call, with the help of an action of the vuex store, to be made each minute to a backend Api (it's triggered when the component is loaded as a route), now let's say I go to an about route that goes to an About component, is FirstPage still making the calls?

Edit:
I'm not developing an app with that yet, so I can't provide examples.
It's on my interest to know the behavior in these cases of the router, because whenever I change the route I would want to stop making the constant calls (as they won't be necessary).
The reason is that Depending on this I'd have to switch tooling for a project I have in mind.

like image 758
sab Avatar asked Oct 12 '18 08:10

sab


People also ask

How do I change my vue route?

To navigate to a different URL, use router. push . This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.

Does vue reuse components?

Since components are reusable Vue instances, they accept the same options as new Vue , such as data , computed , watch , methods , and lifecycle hooks. The only exceptions are a few root-specific options like el .

How does vue routing work?

Vue Router uses special link elements called <router-link> that have a to attribute that map to a component. When we run our app, we should see our home component rendering. If we click our router-link elements, the content will change and the URL will too!


1 Answers

In general, a component's instance will be destroyed when you navigate away from it. However, there are two exceptions to this ..

  1. When you use routes with params. From the Vue Router docs

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.

  1. When you wrap your router-view component within a keep-alive element. Since the <router-view> is essentially a dynamic component.

Generally Vue does a very good job of housekeeping and cleaning up after a component's instance when it gets destroyed. But sometimes you'll have to do some manual cleanup, especially if you use some kind of external library. This is usually handled in the beforeDestroy hook of an instance's lifecycle.

like image 169
Husam Ibrahim Avatar answered Sep 30 '22 04:09

Husam Ibrahim