Use of keep alive of vue

Concept:

Keep alive is a built-in component of 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

  1. deactivated

Called when the keep alive component leaves

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

Life cycle after using keepAlive:
Entering the cache page for the first time: beforerouteenter -- > created -- > mounted -- > activated -- > deactivated
Enter the cache page again: beforerouteenter -- > activated -- > deactivated

Note:
1. Activated here is very useful, because when the page is cached, the created,mounted and other life cycles are invalid. If you want to do some operations, you can complete them within activated (a chestnut will be given below: the list page returns to the last browsing position)
2. Called when the activated keep alive component is activated. The hook is not called during server-side rendering.
3. Called when the deactivated keep alive component is deactivated. This hook will not be called during server-side rendering.

Cache entire project

On 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. On app Settings in Vue: (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. In 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
      	  }
        }
      ]
    }
  ]
})

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

//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 beforeRouteLeave, to Name sets the dynamic cache according to the specific route. 

The list page returns to the last browsing position

//Conditions: 1. Lazy loading and delayed loading of data are not allowed for the list page,
//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')
    }
},

Theory:

Keep alive is a built-in component of Vue. When it wraps dynamic components, it caches inactive component instances instead of destroying them. Keep alive is an abstract component: it does not render itself as a DOM element or appear in the parent component chain.
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

Keywords: Javascript Front-end Vue Vue.js Interview

Added by blackmamba on Mon, 07 Feb 2022 02:25:53 +0200