Basically, I want to keep alive 2 components in router-view and it works, however, I don't know if I am doing it correctly.
<keep-alive include="users, data"> <router-view></router-view> </keep-alive>
users and data are route names. Is this correct way to do it. Are there any disadvantages of keep-alive?
Keep alive is just keeping the current component state and render output in memory. Vue cannot use keep-alive on an iframe because it is a native element - it doesn’t have state.
One neat thing about keep-alive components is that they have special Vue lifecycle hooks. This is necessary because keep-alive components only run their initialization hooks (create and mount) once. To help observe when a kept alive component is toggled, we have two unique hooks – both of which are pretty intuitive:
It stores a cached reference to your component when it’s not active. This means that Vue does not have to create a new instance every single time you switch components. Instead, it just uses the cached reference whenever you come back to it.
We can use keep-alive components to do anything that requires us to keep existing data on the screen. For instance, we can use it to cache user input in forms or cache API call results. The keep-alive component also stores components in a cache, so it rendering faster.
The only disadvantage is that these components are kept in memory and therefore their state is saved and not reset.
You also lose lifecycle hooks like created, mounted, etc. since the component is not being rebuilt from scratch anymore. You can replace those lifecycle hooks with hooks that are specific to keep-alive
components. For example:
https://vuejs.org/v2/api/#activated
Whether keep-alive
is a disadvantage or advantage is entirely up to your scenario. If you want to keep the state because you want to switch fast and often between the keep-alive
components, it could be an advantage. If you really rely on a clean state through components being built and destroyed, it could be a disadvantage.
1. We can achieve it by using `
<keep-alive> // Render component inside </keep-alive>
` special tag which has provided by vueJs.
2. use life cycle hooks:
a. activated()
b. deactivated()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With