[Vue3 Chapter 22] KeepAlive cache component

Preface

During the development of the Vue backend management project, sometimes a tab-like approach is used to place the left menu at the top for quick access.
Insert image description here

The problem is that every time a component is accessed, a new vue component instance will be recreated. When switching components, all network requests of other visited components will be resent. That is to say, a complete Vue life cycle such as created, mounted, and destroyed will be executed again, and all data will be initialized.
Although this is good and can always maintain the latest data, in many business scenarios, we do not want to have such an effect. Another example:
There is a form page now. When I fill in the form, I may need to go back to the previous page to view some information to fill in the form. You follow the convention of using routing to return to the previous page. When you finish viewing the upper level page, When you switch back to the form interface, you will find that the component information is all gone, which is very unfriendly. Next, some means are needed to retain the state of the component, and that is the role of keep-alive.
The advantage of using keep-alive is that the state is retained in memory during component switching, preventing repeated rendering of the DOM, reducing loading time and performance consumption, and improving user experience.

Digital management platform
Vue3+Vite+VueRouter+Pinia+Axios+ElementPlus
permission system-Mall
personal blog address

1. Basic usage

1.1 Overview

Sometimes we don't want components to be re-rendered to affect the user experience; or for performance reasons, we want to avoid multiple re-renderings that reduce performance. Instead, we hope that the component can be cached and maintain its current state. This is when you need to use <KeepAlive>components.

Enable <KeepAlive>life cycle changes

  • When entering for the first time: onMounted> onActivated
  • Deactivated is triggered after exiting
  • Enter again: only onActivated will be triggered

1.2 Code demonstration

<script setup>
    import { ref,shallowRef } from 'vue'
    import CompA from './CompA.vue'
    import CompB from './CompB.vue'

    const current = shallowRef(CompA)
    
    let num = ref(10);
</script>

<template>
  <div class="demo">
    <label><input type="radio" v-model="current" :value="CompA" /> A</label>
    <label><input type="radio" v-model="current" :value="CompB" /> B</label>
  
    <KeepAlive>
    	<!-- 动态组件绑定 is 属性切换 -->
    	<component :is="current"></component>
    </KeepAlive>  
    
    <keep-alive>
    	<!-- 多个条件判断的子组件 -->
        <comp-a v-if="num > 1"></comp-a>
        <comp-b v-else></comp-b>
    </keep-alive>
    
    <!-- 和 Transition 动画组件一起使用 -->
    <transition>
        <keep-alive>
        	<component :is="current"></component>
        </keep-alive>
    </transition>
  </div>
</template>

Event mounting methods, etc., are only executed once and placed in onMounted; methods that are executed each time the component is entered are placed in onActivated.

2. include/exclude

2.1 Overview

<KeepAlive>By default, all internal component instances are cached, but we can customize this behavior through includeand props.exclude

  • include: Include, components contained in this collection or with name values ​​matched by regular expressions will be cached
  • exclude: Check that components whose name value is included in this collection or matched using regular expressions will not be cached.

The value of both props can be a comma-separated string, a regular expression, or an array containing both types.

2.2 Code examples

<!-- 以英文逗号分隔的字符串 -->
<KeepAlive include="a,b">
  <component :is="view" />
</KeepAlive>

<!-- 正则表达式 (需使用 `v-bind`) -->
<KeepAlive :include="/a|b/">
  <component :is="view" />
</KeepAlive>

<!-- 数组 (需使用 `v-bind`) -->
<KeepAlive :include="['a', 'b']">
  <component :is="view" />
</KeepAlive>

include and exclude will return a Boolean value based on the matching value. Of course, this Boolean value is not controlled by you, but is operated internally by the keep-alive component. It will determine how the Boolean value is reflected based on the component name you pass in. It's the difference between simply requiring caching and not requiring caching.

3. max maximum number of cache instances

You can maxlimit the maximum number of component instances that can be cached by passing in a prop. <KeepAlive>behaves like an LRU cache when specified max: if the number of cached instances is about to exceed the specified maximum number, the cached instances that have not been accessed for the longest time will be destroyed to make room for new instances.

<KeepAlive :max="10">
  <component :is="activeComponent" />
</KeepAlive>

It is worth noting here that when the upper limit of the maximum cache component is set, a heap data structure will be formed. When the number of components you set to be cached exceeds the max limit, the elements at the bottom of the heap will be removed. In short, it operates according to the first-in, first-out rule. When the upper limit of cached components is reached, the first cached component will be removed and the new cached component will be pushed to the top of the heap.

4. Life cycle of cache instance

When a component instance is removed from the DOM but is <KeepAlive>still part of the component tree because it is cached, it becomes inactive rather than being unloaded. When a component instance is inserted into the DOM as part of the cache tree, it will be reactivated .

A persistent component can register lifecycle hooks for the corresponding two states through onActivated()and .onDeactivated()

<script setup>
    import { onActivated, onDeactivated } from 'vue'

    onActivated(() => {
      // 调用时机为首次挂载
      // 以及每次从缓存中被重新插入时
    })

    onDeactivated(() => {
      // 在从 DOM 上移除、进入缓存
      // 以及组件卸载时调用
    })
</script>

onActivatedIt is also called when the component is mounted, and onDeactivatedit is also called when the component is unmounted. These two hooks apply not only to <KeepAlive>the root component of the cache, but also to descendant components in the cache tree.

5. Summary

Components wrapped by keep-alive will be retained in the component tree. You can continue to operate the components of other leaf nodes, but the components of other leaf nodes will still go through the complete declaration cycle of creation, generation, and destruction normally. You can revisit them When a component is created, everything is new, and the component wrapped by keep-alive will always grow on the tree and will always exist. In addition to going through creation and generation, it will not be destroyed before the page is unloaded. You can simply It is understood that if it is saved in memory like a closure, it will not die. In Vue, this means that the component is always retained in the virtual DOM, and the state of the component and its descendant components is maintained, but it is not rendered. Here, knock on the blackboard. Note that the component is always retained in the virtual DOM. In the virtual DOM, the state of the component and descendant components is maintained but not rendered. Well, that’s right, the descendant components of the components you introduce will also be cached.

Guess you like

Origin blog.csdn.net/qq_39335404/article/details/129250171