# Use and principle of Vue keepalive

2022-04-29 04:29:02

### vue keepalive The use and principle of

scene ：A->B No need to cache ,C->B Cache required
There are many online solutions , The general idea is to add keepAlive The status value ,app.vue According to this status value, you can judge whether you need to add keepAlive Components ; Leaving A Page access B On the page , Set this status value to false, Leaving C go back to B Set the status value to true

// stay router Add inside mata
{
path: '/b',
name: 'B',
component: B,
meta:{
keepAlive:true
}
}
// stay app.vue in
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive> <router-view v-if="!$route.meta.keepAlive"></router-view>
// stay A On the page
beforeRouteLeave(to, from, next) {
to.meta.keepAlive = false;
next();
}
// stay C On the page
beforeRouteLeave(to, from, next) {
to.meta.keepAlive = true;
next();
}

for the first time A>B>C, And then back to B Words , Will not be cached .
from B To A, Later on B,B Not cached , Behave normally , After clicking on C, This time from C return , What you get is at the beginning B The cache of

Final solution ： utilize keepalive Component's include Parameters , coordination vuex State management , Dynamically add pages that need to be cached . The specific way is to vuex Defines an array to store pages that need to be cached name value , Then guard the route beforeEach Function to listen for the page to jump to , And put the page that needs to be cached name Value deposit vuex In the array , When B->A when , Delete stored in vuex Array name.
General principles ： As long as it is B page （ Pages to cache , All cached ）, Before returning to A Clear the corresponding cache when name

Source code

vue edition ：2.6.11
Source location ：src->core->components->keep-alive.js

Create a stage ：created It will create a cache object , For preservation vnode node
Destruction phase ：destroyed The hook will call pruneCacheEntry Method to remove cache All component instances in the cache
Rendering phase ：
1、 Gets the... Of the current component name value
2、 take name adopt include And exclude Property to match , The match didn't work （ Indicates that caching is not required ） Then return directly vnode
3、 If there is a cache, take the component instance in the cache , If not, cache the component
4、 If the cache exceeds the maximum value, the first cache will be deleted

If there is a right include and exclude Modification of , that watch The Commissioner heard the change , Then update accordingly cache The value in .
So the above question is easy to explain , On the route mate Adding a status value to it doesn't actually look like include It's like this watch Listen to the , So there will be problems .