What is thekeep-alive

In normal development, some components do not need to be initialized more than once. In this case, we need to persist the components so that the state of the components remains the same and the components will not be re-initialized in the next presentation.

That is, Keepalive is a component built into Vue that can keep contained components in state or avoid re-rendering. This is known as component caching


is a built-in component of Vue that keeps state in memory during component switching, preventing repeated DOM rendering.


when wrapping dynamic components, inactive component instances are cached rather than destroyed. Like
,

is an abstract component: it does not render a DOM element on its own, nor does it appear in the parent component chain.

prop:

  • Include: string or regular expression. Only matching components are cached.
  • Exclude: indicates a string or regular expression. Any matching components will not be cached.

keep-aliveThe declaration cycle is executed

  • The sequence in which the hooks are triggered when the page is first entered

Created -> Mounted -> activated Deactivated Specifies the value that is activated when the device exits from the system

  • The event mount method, etc., is only performed once in placemounted; The method that the component executes each time it goes in is placedactivated;

Basic usage

<! Keepalive-contained components are cached -->
<keep-alive>
    <component><component />
</keep-alive>
Copy the code

Keepalive-contained components are not re-initialized, meaning that the lifecycle function is not reinitialized. However, sometimes we want cached components to be able to render again. Vue solves this problem for us. There are two more lifecycle hooks: activated and deactivated:

  • activatedkeepaliveTriggered when the contained component is rendered again
  • deactivatedkeepaliveTriggered when the contained component is destroyed

Keepalive is an abstract component. Cached components are not mounted, so the activated and deactivated hooks are provided

Parameters to understand

Keepalive can receive three attributes as parameters for matching the corresponding component cache:

  • Include components (can be strings, arrays, and regular expressions; only matching components are cached)

  • Exclude components (strings, arrays, and regular expressions that match are not cached)

  • Max Maximum number of cache components (characters or numbers can be used to control the number of cache components)

Note: This is mandatory when using regular expressions or arraysv-bind

<! Caches (only) components whose name is A or B, and uses them with dynamic components -->
<keep-alive include="a,b">
  <component></component>
</keep-alive>

<! -- Component with component name C is not cached (can preserve its state or avoid re-rendering) -->
<keep-alive exclude="c"> 
  <component></component>
</keep-alive>

<! To use regular expressions, use v-bind -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>

<! -- Dynamic judgment -->
<keep-alive :include="includedComponents">
  <router-view></router-view>
</keep-alive>

<! -- Exclude takes precedence over include if both include and exclude are used.
<keep-alive include="a,b" exclude="b"> 
  <component></component>
</keep-alive>

<! If the number of cached components exceeds the value set by Max 5, the first cached component will be deleted.
<keep-alive exclude="c" max="5"> 
  <component></component>
</keep-alive>
Copy the code

meetvue-routerIn combination withrouterUse, cache part of the page

View components under all paths are cached

<keep-alive>
    <router-view>
        <! All view components that match paths are cached! -->
    </router-view>
</keep-alive>
Copy the code

If you just wantrouter-viewIf a component is cached, what should I do?

  • useinclude/exclude
  • usemetaattribute

1, include (exclude)

Disadvantages: You need to know the name of the component, not a good choice when the project is complex

<keep-alive include="a">
    <router-view>
        <! -- only include a matched path will be cached -->
    </router-view>
</keep-alive>
Copy the code

2. Use meta attributes

Advantages: There is no need to cite component names that need to be cached

Use the keepAlive attribute of $route.meta:

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

You need to set the meta of the router in the router:

/ /... router.js
export default new Router({
  routes: [{path: '/'.name: 'Hello'.component: Hello,
      meta: {
        keepAlive: false // No caching is required}}, {path: '/page1'.name: 'Page1'.component: Page1,
      meta: {
        keepAlive: true // Need to be cached}}}])Copy the code

Use router. Meta extension

Suppose there are three routes: A, B, and C.

  • Requirements:

    • Default: A
    • B jumps to A, but A does not refresh
    • C jumps to A, and A refreshes
  • implementation

    • Set the meta attribute in route A:
{
        path: '/'.name: 'A'.component: A,
        meta: {
            keepAlive: true // Need to be cached}}Copy the code
  • Set beforeRouteLeave in component B:
export default {
        data() {
            return {};
        },
        methods: {},
        beforeRouteLeave(to, from, next) {
             // Set the meta of the next route
            to.meta.keepAlive = true;  // let A cache, i.e., not refreshnext(); }};Copy the code
  • Set beforeRouteLeave in C component:
export default {
        data() {
            return {};
        },
        methods: {},
        beforeRouteLeave(to, from, next) {
            // Set the meta of the next route
            to.meta.keepAlive = false; // let A not cache, that is, refreshnext(); }};Copy the code

This will enable B to return to A, A does not refresh; If C goes back to A, refresh.

Pit prevention guidelines

1. Keep-alive matches the name field of the contained component first. If name is not available, it matches the registered name in the current component components configuration. 2. Keep-alive does not work properly in functional components because they do not cache instances. 3. If the matching conditions include include and exclude, exclude has the highest priority (current Vue 2.4.2 version). For example, if the inclusion and exclusion matches component A, then component A will not be cached. 4. It is included in keep-alive, but complies with exclude and does not invoke activated and deactivated.

Realize forward refresh, backward do not refresh

Thanks to IceUncle for sharing vue refreshes forward, Refreshes Backward.

conclusion

Router.go (-1) is the route to the router, and no additional parameters are required.

Keep-alive does not cache effectively in non-single page applications

The keep-alive hook functions can be activated or deactivated


keeps data in memory. If you want to fetch the latest data every time you enter the page, you need to fetch data in the Activated phase, which is used to fetch data in the original Created hook.

The appendix

Lifecycle functions: These are functions that vUE executes automatically at certain times

  1. BeforeCreate (){} neither data nor methods are initialized

  2. Created (){} Data and methods are initialized. If you want to call methods or manipulate data, you can only operate in Created.

  3. BeforeMount (){} indicates that the template has been edited in memory but has not yet been rendered to the template page. The elements in the page are not actually replaced, just some template string that was written earlier.

  4. Mounted (){} Specifies that the template is mounted to the page. The displayed page is displayed

  • Note that this is the last function of a lifecycle function, which means that the entire Vue instance has been initialized and the component is out of the creation phase and into the run phase.

  • Here are the hooks for the two lifecycle functions at run time:

  1. BeforeUpdate (){} means that our interface is not yet updated but the data in data is up to date. That is, the page has not been synchronized with the data in the latest data.

  2. Updated (){} updated(){} indicates that the page and data are updated.

  3. BeforeDestory (){} When this lifecycle hook is executed the vue instance goes from run to destroy when data and methods are available on the instance.

  4. Destoryed (){} indicates that the component has been completely destroyed and all instance methods in the component are unusable

Reference:

  • issues#811
  • vue#keep-alive
  • Vue2.0 keep-alive best practices