Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use keep-alive in vuejs?

Tags:

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?

like image 859
lejhbah Avatar asked Jan 29 '18 13:01

lejhbah


People also ask

What is the use of keep alive in Vue?

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.

What are the keep-alive lifecycle hooks in Vue?

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:

What is a cached component in Vue?

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.

What is the use of keep alive component?

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.


2 Answers

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.

like image 88
Stephan-v Avatar answered Sep 20 '22 09:09

Stephan-v


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()

like image 28
Pramod Kharade Avatar answered Sep 19 '22 09:09

Pramod Kharade