The role of keep alive in vue and the understanding of activated and deactivated life cycles

Posted by reaper7861 on Wed, 12 Jan 2022 07:59:15 +0100

Keep alive introduction

Keep alive # is a built-in component of Vue, which can keep the contained components in the state or avoid re rendering.

usage

<keep-alive>
  <component>
    <!-- This component will be cached! -->
  </component>
</keep-alive>

props

  • include - string or regular expression. Only matching components will be cached
  • exclude - string or regular expression. Any matching components will not be cached


2.1.0 NEW

The include and exclude attributes 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  (use `v-bind`) -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>
 
<!-- array (use `v-bind`) -->
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>

 




max

2.5.0 NEW

The maximum number of component instances that can be cached. Once this number is reached, the longest unreachable instance in the cached component will be destroyed before the new instance is created.

<keep-alive :max="10">
  <component :is="view"></component>
</keep-alive>
<keep-alive> Does not work in functional components because they do not have cached instances.



// assembly a
export default {
  name: 'a',
  data () {
    return {}
  }
}

 

<keep-alive include="a">
  <component>
    <!-- name by a Your components will be cached! -->
  </component>
</keep-alive>You can preserve its state or avoid re rendering

<keep-alive exclude="a">
  <component>
    <!-- except name by a All components will be cached! -->
  </component>
</keep-alive>You can preserve its state or avoid re rendering

 

But in the actual project, it needs to be used together with Vue router

Router view is also a component. If it is directly wrapped in keep alive, all view components matching the path will be cached:

<keep-alive>
    <router-view>
        <!-- All view components that match the path will be cached! -->
    </router-view>
</keep-alive>

What if you only want a component in router view to be cached?

// routes to configure
export default [
  {
    path: '/',
    name: 'home',
    component: Home,
    meta: {
      keepAlive: true // Need to be cached
    }
  }, {
    path: '/:id',
    name: 'edit',
    component: Edit,
    meta: {
      keepAlive: false // No need to be cached
    }
  }
]

<keep-alive>
    <router-view v-if="$route.meta.keepAlive">
        <!-- Here are the view components that will be cached, such as Home! -->
    </router-view>
</keep-alive>

<router-view v-if="!$route.meta.keepAlive">
    <!-- Here are view components that are not cached, such as Edit! -->
</router-view>
 
 
Activated and deactivated (executed when the component is activated and deactivated)

These two hooks need to be used together with < keep alive > < keep alive / >
Keep alive caches inactive component instances instead of destroying them. When the component is switched in < keep alive >, the activated and deactivated life cycle hook functions will be executed correspondingly.


Note: the two life cycle functions activated and deactivated must be available only after the keep alive component is used, otherwise they do not exist. When keep alive is introduced, the page enters for the first time, and the trigger sequence of the hook is created - > mounted - > activated. When exiting, deactivated is triggered. When entering (forward or backward) again, only activated is triggered.

Illustrate with an example:

Set up a scaffold, create 2 sub components and 1 parent component

Sub component A content

<template>
    <div>
        <div>componentA</div>
        <button @click="show=!show" >componentA event</button>
        <div v-if='show'>componentA-2</div>
        <div v-else>componentA-1</div>
    </div>
</template>
<script>
    export default {
        name: 'componentA',
        comments: {},
        data() {
            return {
                show: true,
                circle:'life cycle'
            }
        },
        activated() {
            console.group("activated Execute when component is active ");
        },      
        deactivated() {
            console.group("deactivated Execute when component is deactivated");
        }
    }
</script>
<style>
</style>

 

Sub component b content:

<template>
    <div>
        <div>componentB</div>
    </div>
</template>
<script>
    export default {
        name: 'componentB',
        compnents: {},
        data() {
            return {}
        }
    }
</script>
<style>
</style>

Parent component content

<template>
    <div id="box">

        <button @click="active='componentA'">componentA</button>
        <button @click="active='componentB'">componentB</button>
        
        <keep-alive>
            <component :is='active' ></component>
        </keep-alive>
        
    </div>
</template>
<script>
    import Vue from 'vue'
    import componentA from '@/components/componentA'
    import componentB from '@/components/componentB'

    export default{
        
        components:{
            componentA,
            componentB
        },
        
        data(){
            return{
                active:'componentB'
            }
        }
    }
</script>
<style>
</style>

If

It can be seen here that when component A is clicked to activate, the activated hook will be triggered. When component B is clicked to open and component A is closed, the deactivated hook will trigger execution.

It can also be seen here that in keep alive, the data of component A is also cached, and the component state is not changed again when triggered the second time



 

Topics: Vue.js