vue uses keep alive to cache pages

concept

Keep alive is a built-in component of Vue. When it wraps dynamic components, it caches inactive component instances instead of destroying them. Like transition, keep alive is an abstract component: it does not render itself as a DOM element, nor does it appear in the parent component chain.

effect

In the process of component switching, the switched components are kept in memory to prevent repeated rendering of DOM, reduce loading time and performance consumption, and improve user experience

principle

When the created hook function is called, save the VNode nodes to be cached in this.cache / when rendering (page rendering), if the VNode name meets the caching conditions (can be controlled by include and exclude), the previously cached VNode instances will be taken from this.cache for rendering.

VNode: virtual DOM is actually a JS object

Parameters (Props)

include - string or regular expression. Only components with matching names are cached.
exclude - string or regular expression. Any component whose name matches will not be cached.
max - number. How many component instances can be cached at most

Change of life cycle function

Components created in keep alive will have two more life cycle hooks: activated and deactivated

  1. activated
    Called when the keep alive component is activated

  2. deactivated
    Called when the keep alive component leaves

Normal life cycle: beforeRouteEnter --> created --> mounted --> updated -->destroyed

use keepAlive Post life cycle:
Entering the cache page for the first time: beforeRouteEnter --> created --> mounted --> activated --> deactivated
 Enter the cache page again: beforeRouteEnter --> activated --> deactivated

Note:
1,there activated Very useful because when a page is cached, created,mounted If you want to perform some operations after the life cycle fails, you can activated Internal completion(Here is a chestnut: the list page returns to the last browsing position)
2,activated   keep-alive Called when the component is activated, the hook is not called during server-side rendering. 
3,deactivated   keep-alive Called when the component is deactivated, the hook will not be called during server-side rendering.

Cache entire project

In App.vue

// If you need to cache the whole project, set the following settings (just wrap the root router view directly):
<template>
  <div id="app">
  	<keep-alive>
      <router-view/>
    </keep-alive>
  </div>
</template>
<script>
export default {
  name: 'App'
}
</script>

Cache some pages in combination with Router

// 1. Set in App.vue: (switch mode according to whether caching is required)
<keep-alive>
    <router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>

// 2. Set on the router.js routing page:
new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
      redirect: 'goods',
      children: [
        {
          path: 'goods',
          name: 'goods',
          component: Goods,
          meta: {
        	keepAlive: false // No cache required
      	  }
        },
        {
          path: 'ratings',
          name: 'ratings',
          component: Ratings,
          meta: {
        	keepAlive: true  // Cache required
      	  }
        },
        {
          path: 'seller',
          name: 'seller',
          component: Seller,
          meta: {
        	keepAlive: true  // Cache required
      	  }
        }
      ]
    }
  ]
})

Note:

A page configured with keepAlive will not be re rendered when entering again, and the components in the page will not be rendered again. This may cause relevant operations within the component (those that need to re render the page every time: such as value transfer between parent and child components) to no longer take effect. This may lead to some inexplicable and unverifiable bug s

Use the new attribute include/exclude to cache some pages

// vue2.1.0 adds two attributes, include and exclude, to allow components to cache conditionally. Both can be represented by comma separated strings, regular expressions, or an array.
<!-- Comma separated string -->
<keep-alive include="a,b">
    <component :is="view"></component>
</keep-alive>
 
<!-- regular expression  (need `v-bind`binding) -->
<keep-alive :include="/a|b/">
    <component :is="view"></component>
</keep-alive>
 
 <!-- array (need `v-bind`binding) -->
<keep-alive :include="['a', 'b']">
    <component :is="view"></component>
</keep-alive>

//Note: first, check the name option of the component itself. If the name option is unavailable, match its local registered name (the key value of the parent component components option). Anonymous components cannot be matched.
Dynamic judgment, using v-bind:include
<keep-alive :include="includedComponents">
    <router-view></router-view>
</keep-alive>
// includedComponents can be set dynamically 
Use before route leave or after each to intercept
// As set in the Category component of the project:
beforeRouteLeave(to,from,next){
    if(to.name=='DemoIndex'){
        if(!from.meta.keepAlive){
            from.meta.keepAlive=true
        }
        next()
    }else{
        from.meta.keepAlive=false
        to.meta.keepAlive=false
        next()
    }
},
// In beforeroutleave, to.name sets the dynamic cache according to the specific route. 
The list page returns to the last browse position
//Conditions: 1. The list page cannot use lazy loading to delay loading data. 2. The list page needs to use keepAlive cache

beforeRouteLeave(to,from,next){  
//Store the height in sessionStorage before leaving the page. localStorage is not recommended here because the session will be cleared automatically when the browser is closed, while local needs to be cleared manually, which is a little troublesome.
    sessionStorage.setItem('scrollH',document.getElementById('demo').scrollTop)
    next()
},

activated(){   
    //During the activated life cycle, the height value is read from sessionStorage and set to dom
    if(sessionStorage.getItem('scrollH')){
        document.getElementById('demo').scrollTop=sessionStorage.getItem('scrollH')
    }
}

Tags: Javascript Vue

Posted on Sat, 27 Nov 2021 22:55:17 -0500 by Takuma