Cache component status in vuejs-keepAlive

b9f02a5b85d05f77d1cdb7467819c735.jpeg

Preface

Invuejs, we often need to cache the status of some components. For example, after a user logs in, switches to other pages, and then switches back, the previous login status needs to be retained instead of restarting. Log in.

Or when switching between different components, you need to retain the previous component state instead of reloading. If you set nothing

You will find that all previously changed states have been reset.

It usually makes sense to create new component instances when switching, but in some cases we really want components to retain their state when being "switched away". To solve this problem, we can wrap these dynamic components with <KeepAlive> built-in components

code example

<!-- 非活跃的组件将会被缓存! -->
<KeepAlive>
  <component :is="activeComponent" />
</KeepAlive>

Include and exclude

<KeepAlive> will cache all internal component instances by default, but we can control the components through include and exclude's prop Caching or not caching. Both prop values ​​can be a comma-separated string, a regular expression, or an array containing both types

<!-- 以英文逗号分隔的字符串,a,b代表的是组件 -->
<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>

It will be matched according to the component's name option, so if the component wants to be conditionally cached by KeepAlive, it must explicitly declare a < /span>nameoption

Precautions

Single file components using<script setup> will automatically generate the corresponding name options based on the file name, no need to manually declare

Before front-end and back-end joint debugging - a front-end’s thoughts before hand-writing code

2023-09-21

09ce05f1da4a4e16a4ee51e85324a3ed.jpeg

How to tell if a girl is a prude

2023-09-20

161a6e4088c09c9dae83766228935b8a.jpeg

vue3+vite installation element-plus error report solution - using components does not work

2023-09-18

a1b047920cc29b81d45c8676a5655300.jpeg

How to solve cross-domain problems when the local development environment built by vite requests a third-party interface

2023-09-17

5eb8baf6bd2a6de2d38cc2fad67bd4c6.jpeg

How does a VuePress website use axios to request a third-party interface?

2023-09-16

98e51bfde066aa70358ba8e674f008bb.jpeg

Front-end and back-end development interface joint debugging and docking parameters

2023-09-13

5d4a8fcefef918ea632cf74c98c81a99.jpeg

Implementing 3D panoramic room viewing in Vue

2023-09-11

875196e8a369dc67ad0252eaedb0448e.jpeg

Guess you like

Origin blog.csdn.net/wzc_coder/article/details/133446070