vue uses keep alive to cache page optimization projects

concept

Keep alive yes Vue When it wraps dynamic components, it caches inactive component instances instead of destroying them. Similar to transition, keep alive is an abstract component: it does not render itself as a DOM element or 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 node to be cached in this In cache / in render (page rendering), if the name of VNode meets the cache conditions (can be controlled by include and exclude), it will be from this Fetch the previously cached VNode instance from the cache for rendering.

VNode: virtual DOM is actually a JS object

Parameters (Props)

  • include - string or regular expression. Only components with matching names will be 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(Let's take 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, and the hook will not be called during server-side rendering.

Cache entire project

App Vue inside

If you need to cache the entire project, set the following settings(Direct wrapping root router-view that will do): 
<template>
  <div id="app">
  	<keep-alive>
      <router-view/>
    </keep-alive>
  </div>
</template>use keepAlive What changes have taken place in the post life cycle



<script>
export default {
  name: 'App'
}
</script>

Cache some pages in combination with Router

1,stay App.vue Medium setting: (switch mode according to whether cache 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,stay router.js Routing page settings:
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 re rendered in the same way. 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 Added include,exclude Two properties that 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: matching first checks the of the component itself name Option, if name If the option is not available, match its local registration name (Parent component components Key value of option). Anonymous components cannot be matched.

Dynamic judgment, using v-bind:include

<keep-alive :include="includedComponents">
    <router-view></router-view>
</keep-alive>
includedComponents Dynamic setting is enough  

Use before route leave or after each to intercept

In projects such as Category Settings in components:
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()
    }
},
stay beforeRouteLeave in to.name Set the dynamic cache according to the specific route. 

The list page returns to the last browsing position

Conditions: 1. Lazy loading and delayed data loading are not allowed for the list page. 2. The list page needs to be used keepAlive cache

beforeRouteLeave(to,from,next){  //Store the height in sessionStorage before leaving the page. It is recommended to clear local session manually, but it is not necessary to clear local session manually.
    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')
    }
},

Keywords: Javascript Vue.js Cache

Added by fert on Tue, 15 Feb 2022 15:15:57 +0200