Introduction: The first article in August, starting from the component cache in VUE, takes advantage of the August activity to strengthen the basic skills of VUE.

When do you need a component cache?

Situation: When we browse articles in nuggets, for example, when you open my article, no matter it is recommendation, selection or attention module, when you read the article, your hand slips, you return to the homepage by mistake, but the home page is reloaded, and the previous module will be deleted from memory, because of the route jump. This causes the component to be destroyed and rebuilt (e.g. /detail jumps to /home,/detail is destroyed,/ home is created). In this way, the user experience is much worse, so a good user experience is to click back and return to the previous module. Optimization: Cache components with keep-alive components.Copy the code

What is component caching?

If components are cached, once they are created, they will not be destroyed when they are switched. The code implementation is actually very simple, is to use the keep-alive tag to package the route exit tag.

<keep-alive>
 <router-view ></router-view>
</keep-alive>
Copy the code

What’s wrong with that?

Problem 1: If too many components are cached, or unnecessary components are cached, too much memory will be occupied. Problem 2: If the detail component is cached, it will not be updated. Strategy: Cache components that are important, frequently used (like the home page), or don't change much. Solution: Mark the route to be cached, and then dynamically decide whether to cache the route when it is loaded. More precise control over which components to cacheCopy the code

The best way to write component caching is:

When defining routes, add additional routes[Meta information]To supplement some information elements.

{ path: '/', component: () => import('.. /views/home/index.vue'), // Whether to cache meta: {isKeepAlive: true}},Copy the code

In app.vue, components are cached based on meta-information

<div id="app"> <keep-alive> <router-view v-if="$route.meta.isKeepAlive"/> </keep-alive> <router-view v-if="! $route.meta.isKeepAlive"/> </div>Copy the code

END

Practice makes perfect, shortage in one; Success depends on forethought, destroyed by. August, come on, everybody.

That’s all about the Vue component cache this time

If you have any questions, please leave a message. Thank you